来自Array的随机Google Maps Marker

时间:2018-04-03 15:43:00

标签: javascript google-maps google-maps-api-3

我正在尝试从Google地图上的数组添加自定义标记我已经看到了与此相关的另一个问题,但所提供的代码并不允许Google Maps API选择标记图标

 function button1(location) {
var get1 = prompt ("Enter First Coord");
var get2 = prompt ("Enter Second Coord");

var icons = [
"https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_green.png",
"https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_purple.png",
"https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_orange.png",
"https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_white.png",
"https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_black.png",
"https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_blue.png"

];
var items;
var center = new google.maps.LatLng(get1,get2);
map.panTo(center);
var marker = new google.maps.Marker({
position: center,
map: map,

icon: items[Math.floor(Math.random()*icons .length)]
});

我一直没有定义"项目未定义"。 如果我在代码上方定义它,我会得到一个不同的错误 "无法阅读财产' 3'未定义"在图标上:items [Math.floor(Math.random()* icons .length)] code

如果有人知道解决方案,我将非常感谢,谢谢!

1 个答案:

答案 0 :(得分:1)

您正在尝试获取空变量items的内容...替换

icon: items[Math.floor(Math.random()*icons .length)]

使用:

icon: icons[Math.floor(Math.random()*icons .length)]

因为您没有在变量items中保存图片,而是在变量icons中保存了图片。