谷歌地图API第3版:从数组中添加标记不起作用 [英] Google Maps API v3: Adding markers from an array doesn't work
问题描述
首先感谢为考虑来回答这个:)大部分AP preciated!
我已经创建使用以下code地图,这个完美的作品。
函数初始化(){ VAR的MapOptions = {
变焦:5,
中心:新google.maps.LatLng(48.160,-6.832)
disableDefaultUI:真实,
mapTypeId设为:google.maps.MapTypeId.ROADMAP
}; 地图=新google.maps.Map(的document.getElementById('map_canvas提供')的MapOptions);
setMarkers(地图,市);
}
但后来我想这个数组在每个城市的标志(请不要建议改变这个作为code这一块确切解决了另一个问题,我有,当然,除非绝对neccesary的):
VAR城市= {
格罗宁根':[53.216723950863425,6.560211181640625,7]
'旧金山':[34.01131647557699,-118.25599389648437,5]
纽约城:40.7143528,-74.0059731,3] };
和我使用这个code放置的实际标记(这是不工作的部分):
函数setMarkers(地图,位置){
//添加标记到地图 对于(VAR I = 0; I< cities.length;我++){
VAR数据=城市由[i]
VAR的标记=新google.maps.Marker({
位置:新google.maps.LatLng(数据[0],数据[1]),
地图:地图,
图标:图像,
标题:测试,
});
}
}
城市
不是一个数组而是一个对象,所以你不能用
为(VAR I = 0; I< cities.length;我++){
// ...
}
使用这个代替
的(城市VAR键){
VAR数据=城市[关键]
VAR的标记=新google.maps.Marker({
位置:新google.maps.LatLng(数据[0],数据[1]),
地图:地图,
图标:图像,
标题:测试,
});
}
first of all thanks for considering to answer this :) Much appreciated!
I've created a map using the following code, and this works perfectly.
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(48.160, -6.832),
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
setMarkers(map, cities);
}
But then I want markers at each of the cities in this array (please don't suggest changing this as this exact piece of code solves another problem I had, unless of course absolutely neccesary):
var cities = {
'Groningen': [ 53.216723950863425, 6.560211181640625, 7],
'San Francisco': [ 34.01131647557699, -118.25599389648437, 5],
'New York City': [ 40.7143528, -74.0059731, 3]
};
And I'm using this code to place the actual markers (which is the part that doesn't work):
function setMarkers(map, locations) {
// Add markers to the map
for (var i = 0; i < cities.length; i++) {
var data = cities [i]
var marker = new google.maps.Marker({
position: new google.maps.LatLng (data[0], data[1]),
map: map,
icon: image,
title: 'test',
});
}
}
cities
isn't an array but an object so you can't use
for (var i = 0; i < cities.length; i++) {
//...
}
Use this instead
for (var key in cities) {
var data = cities[key];
var marker = new google.maps.Marker({
position: new google.maps.LatLng (data[0], data[1]),
map: map,
icon: image,
title: 'test',
});
}
这篇关于谷歌地图API第3版:从数组中添加标记不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!