baoqger baoqger - 6 months ago 49
AngularJS Question

Angular Google Maps: can't get the LatLng from click event object

In my app, after a click on the google map, I need to get the lat and lng information for further handling. And since the app use angularJs as the framework, I used the Angular Google Maps library for maps. My code is as following:

$scope.map = {
center: {
latitude: 37.782551,
longitude: -122.445368
},
zoom: 12,
heatLayerCallback: function (layer) {
MockHeatLayer(layer);
},
showHeat: true,
// the issue is from here
onclick: {
click : function(maps, event, arguments) {
console.log(event.latLng); //return undefined
console.log(typeof(event)); //return string type instead of event object
}
}
};


and HTML tag is as following:

<ui-gmap-google-map center='map.center' zoom='map.zoom' events='map.onclick'>
<ui-gmap-layer namespace="visualization" type="HeatmapLayer" show="map.showHeat" onCreated="map.heatLayerCallback"></ui-gmap-layer>
</ui-gmap-google-map>


as you can see, I set the
events
to
onclick
in the
map
array.

But after debugging, the the
event
in the handle function is a string instead of object, so what is the problem?

Answer

According to the documentation, you have to provide events array, not onclick array. Also the second argument is eventName which is supposed to be string, because event object is in the third argument. From docs:

The handler function takes three parameters: 1. maps: the GoogleMap 2. object eventName: the name of the event 3. arguments: the arguments provided by Google Maps for this event type.

So instead of onclick: { ... in your code, put this:

events: {
     click : function(maps, eventName, arguments) {
          var e = arguments[0];
          var lat = e.latLng.lat(), lng = e.latLng.lng();
          console.log("my lat is:" + lat + ", lng is:" + lng);
     }
}