13

I am using th newest version of the API (v7), and would like to add a pushpin on mouse-click ...

var mapSettings = {
    'credentials': 'myCredentials',
    'mapTypeId': Microsoft.Maps.MapTypeId.road,
    'enableSearchLogo': false,
    'showMapTypeSelector': false,
    'showScalebar': false
};

var $map = $('#map');
var map = new Microsoft.Maps.Map($map.get(0), mapSettings);
Microsoft.Maps.Events.addHandler(map, 'click', function (e) {
    var latitude = ?
    var longitude = ?
    var location = new Microsoft.Maps.Location(latitude, longitude);
    var pushpin = new Microsoft.Maps.Pushpin(location, {
        'draggable': true
    });
    map.entites.push(pushpin);
});

As you see, I am stuck within the click-handler: How do I get latitude & longitude of the click?

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
  • for those wondering, in Bing Maps v8 , the location is hanging right off of the callback param ( e ). `e.location n {latitude: 39.29711299974974, longitude: -111.57935390625, altitude: 0, altitudeReference: -1}` – RyBolt Sep 06 '16 at 15:56

1 Answers1

19

Ok, nailed it. Here's the bit of code that you're interested in:

if (e.targetType == "map") {
  var point = new Microsoft.Maps.Point(e.getX(), e.getY());
  var loc = e.target.tryPixelToLocation(point);
  var location = new Microsoft.Maps.Location(loc.latitude, loc.longitude);
  ......
}

e.target.getLocation() only works when the target is a pushpin, infobox, etc. The click on the actual map is different.

binar
  • 1,197
  • 1
  • 11
  • 24
  • nope ... sry `Uncaught TypeError: Cannot call method 'getLocation' of undefined` –  Dec 21 '11 at 14:17
  • I updated answer to use `e.target` instead of `e.entity`. See if that works. I can't test this right now. – binar Dec 21 '11 at 14:25
  • nope ... sry ... `Uncaught TypeError: Object # has no method 'getLocation'` –  Dec 22 '11 at 06:23
  • I seem to get this to work on the map itself, contrary to your statement. Clicking on one of my pushpins results in an error, though (Uncaught TypeError: Object [object Object] has no method 'tryPixelToLocation'). I haven't tested it on infobox because I don't know what that is. – Konrad Viltersten Dec 26 '13 at 17:52
  • `e.target.tryPixelToLocation(point)` returns a Microsoft.Maps.Location object, so there's no need to grab the lat and lon from that to create a new one. – mricci Aug 19 '14 at 05:54