简体   繁体   中英

adding infowindow to google maps

I'm trying to add some infowindow content to my markers on a google map. I can query my server, get some data, put the markers on the map. That works. What doesn't work is that nothing happens when I click on the marker. I would think that the infowindow would popup. Unfortunately, it has been so long since I have done google maps programming, I am effectively starting over. For some reason, the marker's click event is not being called. Any suggestions regarding my dumbness are appreciated. TIA

<script>
    var map, geocoder;
    var Markers = [];
    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
            center: { lat: 0.0, lng: 0.0 },
            zoom: 12
        });
        if (!Modernizr.geolocation) {
            alert("Your browser sucks. Get a new one, maybe one that is up to date and supports GPS.")
            return;
        }
        else {
            navigator.geolocation.getCurrentPosition(show_map);
        }
    }
    function show_map(position) {
        map.setZoom(12);
        var Latitude = position.coords.latitude;
        var Longitude = position.coords.longitude;
        map.setCenter({ lat: Latitude, lng: Longitude });
        var bounds = map.getBounds();
        var url = "/api/xxxxxxxxjsonendpoint";
        var lowerLeft = bounds.getSouthWest();
        var upperRight = bounds.getNorthEast();
        var lat0 = lowerLeft.lat();
        var lng0 = lowerLeft.lng();
        var lat1 = upperRight.lat();
        var lng1 = upperRight.lng();
        var geocoder = new google.maps.Geocoder();
        var data = { LowerLeftLat: lat0, LowerLeftLng: lng0, UpperRightLat: lat1, UpperRightLng: lng1 };
        $.get(url, data, function (result) {
            for (var i = 0; i < result.length; i++) {
                var address = result[i].Address1 + " " + (result[i].Address2 != null ? result[i].Address2 : "") + " " + result[i].City + " " + result[i].Province + " " + result[i].PostalCode + " " + result[i].Country;
                var marker = new google.maps.Marker({
                    position: geocodeAddress(geocoder, map, address),
                    map: map,
                    title: address
                });
                var infowindow = new google.maps.InfoWindow({
                    content: i
                });
                makeInfoWindowEvent(map, infowindow, "test" + i, marker);
            }
        });
    }
    function geocodeAddress(geocoder, resultsMap, address) {
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status === 'OK') {
                resultsMap.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: resultsMap,
                    position: results[0].geometry.location
                });
            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }
    function makeInfoWindowEvent(map, infowindow, contentString, marker) {
        google.maps.event.addListener(marker, 'click', function () {
            infowindow.setContent(contentString);
            infowindow.open(map, marker);
        });
    }
</script>

Here is the most recent update of my code. Still no worky........

<script>
    var map, geocoder;
    var Markers = [];
    var infowindow;
    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
            center: { lat: 0.0, lng: 0.0 },
            zoom: 12
        });
        infowindow = new google.maps.InfoWindow();
        if (!Modernizr.geolocation) {
            alert("Your browser sucks. Get a new one, maybe one that is up to date and supports GPS.")
            return;
        }
        else {
            navigator.geolocation.getCurrentPosition(show_map);
        }
    }
    function show_map(position) {
        map.setZoom(12);
        var Latitude = position.coords.latitude;
        var Longitude = position.coords.longitude;
        map.setCenter({ lat: Latitude, lng: Longitude });
        var bounds = map.getBounds();
        var url = "/api/xxxxxxx/yyyyyyyyyy";
        var lowerLeft = bounds.getSouthWest();
        var upperRight = bounds.getNorthEast();
        var lat0 = lowerLeft.lat();
        var lng0 = lowerLeft.lng();
        var lat1 = upperRight.lat();
        var lng1 = upperRight.lng();
        var geocoder = new google.maps.Geocoder();
        var data = { LowerLeftLat: lat0, LowerLeftLng: lng0, UpperRightLat: lat1, UpperRightLng: lng1 };
        $.get(url, data, function (result) {
            for (var i = 0; i < result.length; i++) {
                var address = result[i].Address1 + " " +
                    (result[i].Address2 != null ? result[i].Address2 : "") +
                    " " + result[i].City + " " + result[i].Province + " " +
                    result[i].PostalCode + " " + result[i].Country;
                var marker = new google.maps.Marker({
                    position: geocodeAddress(geocoder, map, address),
                    map: map,
                    title: address,
                    content: address
                });

                makeInfoWindowEvent(infowindow, "test" + i, marker);
            }
        });
    }
    function geocodeAddress(geocoder, resultsMap, address) {
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status === 'OK') {
                resultsMap.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: resultsMap,
                    position: results[0].geometry.location
                });
            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
    }
    function makeInfoWindowEvent(infowindow, contentString, marker) {
        (function (zinfowindow, zcontentString, zmarker) {
            zinfowindow.setContent(zcontentString);
            google.maps.event.addListener(zmarker, 'click', function () {
                zinfowindow.open(map, zmarker);
            });
        })(infowindow, contentString, marker);
    }
</script>
function makeInfoWindowEvent(map, infowindow, contentString, marker) {
    infowindow.setContent(contentString);
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.open(map, marker);
    });
}

Your code crash because when the listener is calling, the value of marker and infowindow have already changed. You can try something like this (just change the makeInfoWindowEvent function):

function makeInfoWindowEvent(map, infowindow, contentString, marker) {
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent(contentString);
        infowindow.open(map, marker);
        console.log (contentString);
        console.log (marker);
    });
}

Normally, the output will be always the same for contentString and marker .

In order to pass the real value of the marker , contentString and infowindow , you have to create an IIFE . Like this, the value of the variables will be copy inside the function:

function makeInfoWindowEvent(map, infowindow, contentString, marker) {
    (function (zinfowindow, zcontentString, zmarker) {
       zinfowindow.setContent(zcontentString);
       google.maps.event.addListener(zmarker, 'click', function () {
         zinfowindow.open(map, zmarker);
       });
    })(infowindow, contentString, marker);
}

However, you do not need to pass map as parameter because the value of map is always the same.

Tell me if you have some questions.

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