2012-08-09 21 views
0

试图在googlemap上加载两个标记,但看起来地图加载了两次,我不能看到两个标记。这里是代码。无法加载谷歌地图上的两个标记。每个循环

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

我不知道如何解决这个

+0

因为你叫'新google.maps.Map()'对每个迭代相同的canvas元素它的满载两次。 – Pointy 2012-08-09 12:38:54

回答

1

你的地图创建是每个循环中..试试这个:

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

现在你创建地图的..加上长和lat到LatLngBounds对象,然后设置地图以适合边界。

Docs on LatLngBounds here

+0

地图的颜色变成了蓝色,并且位置远离这些标记 – 2012-08-09 12:46:24

+0

我该如何更改地图的起始位置,以便在美国和英国的中间之间进行切换。我有一个中心:新的google.maps.LatLng(35.74651,-39.46289),但位置仍然位于地图的中间 – 2012-08-09 12:58:37

+0

'map.fitBounds'中心并缩放地图以适合所有点 – ManseUK 2012-08-09 13:28:28