简体   繁体   中英

Google Maps API v3 marker on click with infowindow

I have problem with infowindow. I create marker when i click on map but i want to show infowindow too. This code not working with this part:

google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map, marker);
});

Here is code below.. Thank for help

var pridat;
var map;

function initialize() {
    var locc = new google.maps.LatLng(49.938682,17.903331);
    var mapOptions = {
        zoom: 14,
        center: locc,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    directionsDisplay.setMap(map);

    var contentwindow = '<div>your point</div>'
    var infowindow = new google.maps.InfoWindow({
        content: contentwindow
    });

    // IF I REMOVE THIS PART -> IT WORKS, BUT WITHOUT INFOWINDOW
    google.maps.event.addListener(marker, 'click', function(){
        infowindow.open(map, marker);
    });
    // END OF PART

    google.maps.event.addListener(map, 'rightclick', function(event) {
        placeMarker(event.latLng);
    });
}

function placeMarker(location) {
    if (marker) {
        marker.setPosition(location);
    } else {
        marker = new google.maps.Marker({
            position: location,
            map: map,
            title: 'My point',
            draggable: true,
        });
    }
}

You should look at the javascript errors when it doesn't work. You are attempting to use "marker" before it exists. If you move the 'click' listener for the marker into the placeMarker function where it exists, and make the infowindow globally accessible, it should work. The code you posted doesn't put any markers on the map.

var pridat;
var map;
var marker = null;
var infowindow = null;
function initialize() {
 var locc = new google.maps.LatLng(49.938682,17.903331);

 var mapOptions = {
    zoom: 14,
    center: locc,
    mapTypeId: google.maps.MapTypeId.ROADMAP
                  }

map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);

var contentwindow = '<div>your point</div>'
infowindow = new google.maps.InfoWindow({
    content: contentwindow
 });

google.maps.event.addListener(map, 'rightclick', function(event) {
placeMarker(event.latLng);
});

}

function placeMarker(location) {
if (marker) {
  marker.setPosition(location);
} else {
 marker = new google.maps.Marker({
      position: location,
      map: map,
      title: 'My point',
      draggable: true,
     });
   // IF I REMOVE THIS PART -> IT WORKS, BUT WITHOUT INFOWINDOW
   google.maps.event.addListener(marker, 'click', function(){
       infowindow.open(map, marker);
   });
 }
}

working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM