我正在尝试在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 :(得分: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);
});
现在你创建一个地图..将long和lat添加到LatLngBounds
对象,然后将地图设置为适合边界。