Google地图-具有独特信息窗口的多个标记

时间:2019-07-03 12:08:15

标签: javascript php google-maps google-maps-api-3 infowindow

我正在为网站上的用户创建地图。它的工作方式是我使用PHP和AJAX获取所有站点的用户地址,然后将这些值作为JSON传递给我的JS,在其中我生成一个以当前用户地址为中心的google map,并在地图上为每个用户标记。此部分目前可以正常使用,但是我正在努力为每个用户生成一个唯一的信息窗口。现在,我对所有标记都获得了相同的信息窗口,如何解决呢?

JS

jQuery(document).ready(function($){
    $.ajax({
        url: ajax_url,
        type: 'post',
        dataType: 'json',
        data: { 
            action: 'map' 
        },
        error : function(response){
            console.log(response);
        },
        success : function(response){
            var mapOptions = {
                zoom: 16,
            }

            var geocoder = new google.maps.Geocoder();
            var infowindow = new google.maps.InfoWindow();

            // current user position
            geocoder.geocode({'address': response.current[0].postcode}, function(results, status){
                map.setCenter( results[0].geometry.location );

                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
            });

            // other users loop
            for( var i = 0; i < response.other.length; i++ ){
                var postcode = response.other[i].postcode;

                geocoder.geocode( {'address': postcode}, function(results, status){
                    var marker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location
                    });

                    google.maps.event.addListener(marker, 'click', function(){
                        infowindow.close(); // Close previously opened infowindow
                        infowindow.setContent( "<div id='infowindow'>"+ postcode +"</div>");
                        infowindow.open(map, this);
                    });
                });
            }

            var map = new google.maps.Map(document.getElementById("buddy_map"), mapOptions);

            return false;
        }
    });
});

PHP

add_action('wp_ajax_nopriv_map', 'addresses');
add_action('wp_ajax_map', 'addresses');


function addresses(){
    global $current_user;

    $address_street = get_user_meta( $current_user->ID, 'shipping_address_1', true );
    $address_city = get_user_meta( $current_user->ID, 'shipping_city', true );
    $address_postcode = get_user_meta( $current_user->ID, 'shipping_postcode', true );
    $address = $address_street . ', ' . $address_city . ', ' . $address_postcode;

    $cur_user[] = array(
        "postcode" => $address
    );

    $other_users[] = array(
        "postcode" => "LS11 6NA"
    );

    $other_users[] = array(
        "postcode" => "LS11 6LY"
    );

    echo json_encode( array( "current" => $cur_user, "other" => $other_users) );

    die();
}

我知道我的PHP文件需要做一些工作,只是做一个草稿即可。

1 个答案:

答案 0 :(得分:2)

您需要在for循环中使用闭包。

您可以在Using closures in event listeners上阅读Google文档。

请参见下面的基本示例,并注意在标记click事件监听器中使用闭包。

function initialize() {

    var mapOptions = {
        zoom: 5,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: new google.maps.LatLng(1, 1)
    };

    var locations = [
        [new google.maps.LatLng(0, 0), 'Marker 1', 'Infowindow content for Marker 1'],
        [new google.maps.LatLng(0, 1), 'Marker 2', 'Infowindow content for Marker 2'],
        [new google.maps.LatLng(0, 2), 'Marker 3', 'Infowindow content for Marker 3'],
        [new google.maps.LatLng(1, 0), 'Marker 4', 'Infowindow content for Marker 4'],
        [new google.maps.LatLng(1, 1), 'Marker 5', 'Infowindow content for Marker 5'],
        [new google.maps.LatLng(1, 2), 'Marker 6', 'Infowindow content for Marker 6']
    ];

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

    var infowindow = new google.maps.InfoWindow();

    for (var i = 0; i < locations.length; i++) {

        var marker = new google.maps.Marker({
            position: locations[i][0],
            map: map,
            title: locations[i][1]
        });

        google.maps.event.addListener(marker, 'click', (function (marker, i) {

            return function () {
                infowindow.setContent(locations[i][2]);
                infowindow.open(map, marker);
            }

        })(marker, i));
    }
}
#map-canvas {
  height: 160px;
}
<div id="map-canvas"></div>

<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize">
</script>

要说明如何使用Geocoder,请参阅以下代码段。正如我在评论中所说,Geocoder服务的QPS限制为每秒50个请求。如果您的位置列表包含50多个项目,则很可能会失败,因为循环将在不到1秒的时间内执行。

function initialize() {

  var geocoder = new google.maps.Geocoder();
  var mapOptions = {
    zoom: 12,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: new google.maps.LatLng(40.718193, -74.001339)
  };

  var locations = [
    ['Marker 1', 'Infowindow content for Marker 1', '10001, USA'],
    ['Marker 2', 'Infowindow content for Marker 2', '10002, USA'],
    ['Marker 3', 'Infowindow content for Marker 3', '10003, USA'],
    ['Marker 4', 'Infowindow content for Marker 4', '10004, USA'],
    ['Marker 5', 'Infowindow content for Marker 5', '10005, USA'],
    ['Marker 6', 'Infowindow content for Marker 6', '10006, USA']
  ];

  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  var infowindow = new google.maps.InfoWindow();

  for (var i = 0; i < locations.length; i++) {

    geocoder.geocode({
      'address': locations[i][2]
    }, (function(locations, i) {

      return function(results, status) {

        var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location,
          title: locations[i][0]
        });

        google.maps.event.addListener(marker, 'click', (function(marker) {

          return function() {

            infowindow.setContent("<div id='infowindow-content'><h3>" + locations[i][1] + "</h3>" + results[0]['formatted_address'] + "</div>");
            infowindow.open(map, marker);
          }

        })(marker));
      }
    })(locations, i));
  }
}
#map-canvas {
  height: 160px;
}
<div id="map-canvas"></div>

<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize">
</script>