Google Maps API v3:从数组添加标记不起作用 [英] Google Maps API v3: Adding markers from an array doesn't work

查看:31
本文介绍了Google Maps API v3:从数组添加标记不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先感谢您考虑回答这个问题:) 非常感谢!

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 不是数组而是对象,所以你不能使用

cities isn't an array but an object so you can't use

for (var i = 0; i < cities.length; i++) {
    //...
}

改用这个

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

这篇关于Google Maps API v3:从数组添加标记不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆