无法从 .each 循环加载谷歌地图上的两个标记
unable to load two markers on google map from .each loop
我试图在谷歌地图上加载两个标记,但似乎地图加载了两次,我看不到两个标记。这是代码。
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 这里
相关文章:
- JQuery合并了keyup和focusout两个函数
- 如何使用 node.js 比较两个 json 数组
- 为复选框javascript指定两个值
- 用每小时的差值填充数组/列表-从下拉列表中给定两个时间值
- 单击时切换两个图像
- 我可以'我似乎不知道如何修复javascript中的两个lint.有人能帮我理解吗
- 基于两个条件退出While循环
- 如何在这里将两个值最低的数字相加
- 组合两个javascript函数
- 如何使用offer/answer交换来自两个对等连接的流
- jsf中两个字符串的颜色代码差异
- 加载两个具有相同父密钥名称的json文件
- 在Qualtrics中,介绍如何动态连接两个滑块
- 访问$.ajax()函数中的两个不同数组
- 如何在three.js上添加两个向量
- 如何在datetimepicker中使用两个验证器
- 如何选择嵌套了两个 .each() 函数的多个元素
- 无法从 .each 循环加载谷歌地图上的两个标记
- 从async.each发送到两个不同的函数
- jQuery .each()方法的两个参数的解释