为什么Google Map Multiple标记“循环”不起作用?

时间:2019-01-30 10:18:21

标签: javascript google-maps for-loop google-maps-markers

我尝试添加多个标记。数据从数据库获取并传递给'initMap'函数,然后正确显示了Map和标记,但问题是 for循环无法正常。我有两个位置,但仅示出一个位置(最近位置)

This is view of now

function initMap(post_obj) {
    //*** json object convert to JS array
            var columns = ['longitude', 'latitude', 'placeName', 'phoneNo'];
    var locations = JSON.parse(post_obj).map(function(obj) {
      return columns.map(function(key) {
        return obj[key];
      });
    });

    var mapProp= {
        center:new google.maps.LatLng(7.8731,80.7718), //locate Sri Lanka
        zoom:7,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        styles: [{
            featureType: 'all',
            stylers: [
                {saturation: -100}, //Grey Color map
                {gamma: 0.50},
            ]

        }]
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),mapProp);

     var marker, i;
     var infowindow = new google.maps.InfoWindow();

    for (i = 0; i < locations.length; i++) {  
        console.log(locations[i][0]);
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][0], locations[i][1]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }

}

'post_obj' 的样子

[{"longitude":"79.92094122685603","latitude":"6.858206289512469","placeName":"refill Place Rika's","phoneNo":""},{"longitude":"6.534608320452274","latitude":"81.19367459766863","placeName":"","phoneNo":""}]

请帮助我找到解决方法。

3 个答案:

答案 0 :(得分:2)

尝试此代码,您还需要从Google获取API密钥。

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
  <title>Google Maps Multiple Markers</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
  <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>
</head> 
<body>
  <div id="map" style="width: 500px; height: 400px;"></div>

  <script type="text/javascript">
   var locations = [
       ['Maradana Railway', 6.929537, 79.866271, 5],
       ['Fort Railway', 6.933456, 79.850435, 4],
       ['Secretariat Railway', 6.931965, 79.846058, 3]
   ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(51.530616, -0.123125),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;
    var markers = new Array();

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      markers.push(marker);

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }

    function AutoCenter() {
      //  Create a new viewpoint bound
      var bounds = new google.maps.LatLngBounds();
      //  Go through each...
      $.each(markers, function (index, marker) {
      bounds.extend(marker.position);
      });
      //  Fit these bounds to the map
      map.fitBounds(bounds);
    }
    AutoCenter();

  </script> 
</body>
</html>

答案 1 :(得分:0)

尝试下面的代码,该代码发布在Google Map v3 With Multiple Markers

<!DOCTYPE html>
<html> 
  <head> 
    <title>Google Map v3 With Multiple Markers & Info Windows</title> 
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false& libraries=places"></script>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>  
    <script type="text/javascript" src="jquery.gmap3.min.js"></script>
  </head> 
  <body>
     <div id="map-canvas" style="width:100%;height:500px;"></div>
     <script type="text/javascript">
        var locations = [
          [1, 6.929537, 79.866271,'Maradana Railway'],
          [2, 6.933456, 79.850435,'Fort Railway'],
          [3, 6.931965, 79.846058,'Secretariat Railway']
        ];

        var map;
        var str = '[';
        for (i = 0; i < locations.length; i++) {
          str += '{ "lat" :"' + locations[i][1] + '","lng" :"' + locations[i][2] + '","data" :"<div class=Your_Class><h4><a href=Your_Link_To_Marker>' + locations[i][3] + '</a></h4></div>"},';
        }
        str = str.substring(0, str.length - 1);
        str += ']';
        str = JSON.parse(str);

        jQuery('#map-canvas').gmap3({
          marker: {
            values: str,
              options: {
                icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png',
                //icon: new google.maps.MarkerImage("marker.png"),
              },
              events: {
                click: function (marker, event, context) {
                  map = $(this).gmap3("get"),
                    infowindow = $(this).gmap3({ get: { name: "infowindow" } });
                  if (infowindow) {
                    infowindow.open(map, marker);
                    infowindow.setContent(context.data);
                  } else {
                    $(this).gmap3({
                    infowindow: {
                      anchor: marker,
                      options: { content: context.data }
                    }
                  });
                }
              },
            }
          },
          map: {
            options: {
              zoom: 14,
              scrollwheel: true,//Make It false To Stop Map Zooming By Scroll
              streetViewControl: true
            },
          },
        });
       </script> 
    </body>
</html>

答案 2 :(得分:0)

有2个错误/错误。

如果将position: new google.maps.LatLng(locations[i][0], locations[i][1]更改为position: new google.maps.LatLng(locations[i][1], locations[i][0],然后显示其他位置(第一位置)。那么我意识到从数据库获得的数据结果也有问题。在数据结果中,一对经度和纬度被交换因此,如果我们更改此代码position: new google.maps.LatLng(locations[i][0], locations[i][1]的索引号,则显示相关的位置标记。

数据库中的结果对象为'post_obj'

[{"longitude":"79.92094122685603","latitude":"6.858206289512469","placeName":"refill Place Rika's","phoneNo":""},{"longitude":"6.534608320452274","latitude":"81.19367459766863","placeName":"","phoneNo":""}]

结果对象的第一个元素是“经度”。因此position: new google.maps.LatLng(locations[i][0], locations[i][1]position: new google.maps.LatLng(locations[i][1], locations[i][0]