Using Google Maps API v3 for the first time and I've got a map with a bunch of markers. I wanted to make it so when you click one, a specific InfoWindow will display (specific to the marker you clicked). I was really surprised that the click event doesn't tell开发者_JAVA百科 you the actual marker that was clicked!
I know there is a solution using a separate method to create a closure but that seems like a hack to me. Is there a better way to do it? Or, is there a way to ask the map "what markers exist at this position" and pass in the position from the event argument?
I expected events to work like this:
google.maps.event.addListener(marker, 'click', function(event, obj)
{
//Now I can work with "obj" - the thing that was clicked.
});
You should just refer to 'this' in the event listener.
google.maps.event.addListener(marker, 'click', function(e) {
// this == marker;
// e == MouseEvent
});
let mousemoveDraw = this.mousemoveDraw.bind(this);
let mousedown_event_DrawPolygonByFinger = this.mousedown_event_DrawPolygonByFinger.bind(this);
let mouseup_event_DrawPolygonByFinger = this.mouseup_event_DrawPolygonByFinger.bind(this);
this.mapInst.addEvents([
{ type: 'mousedown', event : mousedown_event_DrawPolygonByFinger },
{ type: 'mousemove', event: mousemoveDraw },
{ type: 'mouseup', event : mouseup_event_DrawPolygonByFinger }
]);
mapInst - is wrapper on google and yandex map. It is may use this way in callbacak
//event drawing event
mousemoveDraw(event : any){
console.log('mousemoveDraw')
console.log(this)
console.log(this.stateDrawing)
try{
if (this.stateDrawing != 1){
console.log(this.stateDrawing)
let lat = event.latLng.lat();
let lng = event.latLng.lng();
console.log(lat,lng)
this.polyLine.pushCoord({ lat, lng });
}
}catch(e){
console.log('error Polyline.mousemoveDraw : ',e.message);
}
}
How is that a hack when it's provided by the API? What you are describing is a hack. When you click on the marker, it will pass an event which contains the lat & lng.
google.maps.event.addListener(marker, 'click', function(e) {
console.log(e); // { x: 0, y: 0 }
});
I think it would be a mistake to try and hunt down the marker object based on the position of the click event. Using closures to associate the event with a particular marker seems like a valid solution to me. I would create a function that looks something like this:
function createMarker (point, map)
{
var marker = new google.maps.Marker({
position: point,
map: map,
title: "blah"});
marker.stuffOnTheMarker = "Some interesting stuff";
var content = buildSomeContentForThisMarker ();
google.maps.event.addListener(marker, 'click', function() {
infowindow.close ();
infowindow.setContent(content);
infowindow.open(map,marker);
// access the marker than caused this event
alert (marker.stuffOnTheMarker);
});
}
精彩评论