Javascript谷歌地图Api,带有链接的多个标记,只有geocder

Javascript Google Maps Api, multiple markers with links, only geoceder

本文关键字:只有 geocder 链接 Api 谷歌地图 Javascript      更新时间:2023-09-26

我有问题把链接放在多个标记上,我可以在地图上显示我的标记,但是当我尝试把链接放在它们上时,我总是在所有标记上有相同的链接,最后。这里我提供了一个示例代码:

<div id="map" style="height: 400px; width:100%;"></div>
    <script>
    var markers = [{"name":"Vasto","url":"http://www.google.com"},{"name":"Chieti","url":"http://www.wikipedia.com"}];
    var geocoder;
    var map;
    var LatLng;
    var url;
    console.log(markers);
    function initMap() {
        LatLng = {lat: 42.2872297, lng: 13.3403448};
        map = new google.maps.Map(document.getElementById('map'), {zoom: 8, center: LatLng});
        geocoder = new google.maps.Geocoder();
        setMarkers();
    }
    function setMarkers() {
        var marker, i, url;
        for( i = 0; i < markers.length; i++ ) {
            url = markers[i].url;
            geocoder.geocode({'address': markers[i].name}, function(results, status) {
            if (status === 'OK') {
                marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    title: results[0].address_components[0].long_name,
                });
                google.maps.event.addListener(marker, "click", function() {
                    window.location.href = url;
                });
            } else {
            /*console.log('Geocode was not successful for the following reason: ' + status);*/
            }});
        }
    }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&callback=initMap" async defer></script>

解决方案吗?提前感谢

由于异步代码,您需要更改您的代码位

function setMarkers() {
    markers.forEach(function(item) {
        var url = item.url;
        geocoder.geocode({'address': item.name}, function(results, status) {
        if (status === 'OK') {
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                title: results[0].address_components[0].long_name,
            });
            google.maps.event.addListener(marker, "click", function() {
                window.location.href = url;
            });
        } else {
        /*console.log('Geocode was not successful for the following reason: ' + status);*/
        }});
    }
}