2
votes

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);
});
1
You have to make variables lat/lng global. Currently they are local in event listener.Anto Jurković

1 Answers

4
votes

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);
    });