简体   繁体   中英

Displaying latitude and longitude of Google Maps marker in InfoWindow

How do I dynamically update a URL in my Google Maps InfoWindow with the latitude and longitude of my (movable) marker? I can display an InfoWindow at a clicked location, and I can successfully return lat and lng with event.latLng.lat() and event.latLng.lng() , but if I try to use them to define variables and then use those variables in my InfoWindow, I get Uncaught ReferenceError: lat is not defined errors.

var newpostmarker;
var newpost = new google.maps.InfoWindow({
    content: '<a href="/posts/add?lat=' + lat + '&lng=' + lng + '">Add New</a>'
});

function placeNewPostMarker(location) {
    if (newpostmarker) {
        newpostmarker.setPosition(location);
    } else {
        newpostmarker = new google.maps.Marker({
            position: location,
            map: map_canvas,
        });
    }
    newpostmarker.setVisible(false);
}

google.maps.event.addListener(map_canvas, 'click', function (event) {
    var lat = event.latLng.lat();
    var lng = event.latLng.lng();
    alert("Lat=" + lat + "; Lng=" + lng);
    placeNewPostMarker(event.latLng);
    newpost.open(map_canvas, newpostmarker);
});

The variables are unknown when you initialize the InfoWindow. Set the content-property of the InfoWindow in the click -listener.

//infowindow without properties
var newpost = new google.maps.InfoWindow();

google.maps.event.addListener(map_canvas, 'click', function(event) {
        var lat = event.latLng.lat();
        var lng = event.latLng.lng();
        alert("Lat=" + lat + "; Lng=" + lng);
        placeNewPostMarker(event.latLng);
        newpost.setContent('<a href="/posts/add?lat=' + lat + '&lng=' + lng + '">Add New</a>');
        newpost.open(map_canvas,newpostmarker);
    });

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