无法从 .each 循环加载谷歌地图上的两个标记

unable to load two markers on google map from .each loop

本文关键字:两个 each 循环 谷歌地图 加载      更新时间:2023-09-26

我试图在谷歌地图上加载两个标记,但似乎地图加载了两次,我看不到两个标记。这是代码。

    var geocoder;
    var map;
    geocoder = new google.maps.Geocoder();
    //    var address = document.getElementById("address").value;
    //      var user='33936357';
    $.getJSON("http://api.twitter.com/1/users/lookup.json?user_id=33936357,606020001&callback=?", function (data) {
      $.each(data, function (i, item) {
        var screen_name = item.screen_name;
        var img = item.profile_image_url;
        var location = item.location;
        geocoder.geocode({
          address: location
        }, function (response, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            var x = response[0].geometry.location.lat(),
              y = response[0].geometry.location.lng();
            var mapOptions = {
              center: new google.maps.LatLng(x, y),
              zoom: 8,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
            var marker = new google.maps.Marker({
              icon: img,
              title: screen_name,
              map: map,
              position: new google.maps.LatLng(x, y)
            });
          } else {
            alert("Geocode was not successful for the following reason: " + status);
          }
        });
      });
    });

我不知道如何解决这个问题

您的地图创建在每个循环中..试试这个:

// setup the map objects
var geocoder = new google.maps.Geocoder();;
var mapOptions = {
      center: new google.maps.LatLng(0, 0), 
      zoom: 8,
       mapTypeId: google.maps.MapTypeId.ROADMAP
};
// added this 
var bounds = new google.maps.LatLngBounds();
// create the map
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
$.getJSON("http://api.twitter.com/1/users/lookup.json?user_id=33936357,606020001&callback=?", function (data) {
  $.each(data, function (i, item) {
    var screen_name = item.screen_name;
    var img = item.profile_image_url;
    var location = item.location;
    geocoder.geocode({
      address: location
    }, function (response, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var x = response[0].geometry.location.lat(),
          y = response[0].geometry.location.lng(); 
        var myLatLng = new google.maps.LatLng(x, y);
        var marker = new google.maps.Marker({
          icon: img,
          title: screen_name,
          map: map,
          position: myLatLng
        });
        bounds.extend(myLatLng);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  });
  map.fitBounds(bounds);
});

现在你创建一个地图..将长和纬度添加到LatLngBounds对象,然后设置地图以适合边界。

Docs on LatLngBounds 这里