InfoWindow not Displaying

2019-03-04 02:04发布

问题:

I'm trying to have this so that someone clicks on the map, and an infoWindow pops up telling them that latlng. For now, just trying to figure out how to get an infoWindow to come up. I found a similar problem here with markers and edited the function a bit but I'm missing something which I'm sure is simple and I just cannot pin point. Here's the code:

        function InfoWindow(location) {
          if ( marker ) {
            marker.setPosition(location);
          } else {
            marker = new google.maps.infoWindow({
              position: location,
              content: "sam"
            });
          }
        }

        google.maps.event.addListener(map, 'click', function(event) {
          InfoWindow(event.latLng);
        });
                }

Help greatly appreciated! Thanks

回答1:

I am using InfoBubble, it appears better than InfoWindow and it can also be handled easier. Try it.



回答2:

Event is a LatLng

 google.maps.event.addListener(map, 'click', function(event) {
      InfoWindow(event);
    });


回答3:

You were correct in passing the LatLng of the event (event.latLng), not the whole event. To help with the output, I included code that splits the lat and lng up into strings. A couple other things I fixed: needs to be a capital "I" in google.maps.InfoWindow; set the content to new latLng if the window already exists; added the code to actually open the window at the end. This should take care of everything for ya

function InfoWindow(location) {
    var lat = location.lat().toString();
    var lng = location.lng().toString();
    var new_content = "Lat: " + lat + "<br />Long: " + lng
  if ( marker ) {
    marker.setPosition(location);
    marker.setContent(new_content);
  } else {
      marker = new google.maps.InfoWindow({
      position: location,
      content: new_content
    });
  }
  marker.open(map);
}

google.maps.event.addListener(map, 'click', function(event) {
  InfoWindow(event.latLng);
});


回答4:

The Map MouseEvent has a latLng property

google.maps.event.addListener(map, 'click', function(event) 
{
   new google.maps.InfoWindow({
              map:map, 
              content:"coordinates:"+event.latLng.toUrlValue(),
              position:event.latLng});});
}

"map" is a reference to your google.maps.Map.

Tested on this map by pasting this into the address bar, then clicking on the map:

javascript:google.maps.event.addListener(map, 'click', function(event) {new google.maps.InfoWindow({map:map, content:"coordinates:"+event.latLng.toUrlValue(),position:event.latLng});});