google maps api v3 dynamic markers, help getting array to work

时间:2022-03-01 01:03:01

I am trying to create a google map with javascript api v3. I'm not the best with arrays. the tag gets pulled in dynamically from another search and outputs the finding in this format. now I need it to take this format and output it to multiple markers on the map. I am having issues getting the array to output correctly. This the the format I would like output from the array ... any help would be greatly appreciated.

我正在尝试使用javascript api v3创建一个谷歌地图。我对数组不是最好的。标签从另一个搜索中动态拉入,并以此格式输出结果。现在我需要它采用这种格式并将其输出到地图上的多个标记。我有问题让数组正确输出。这是我想从阵列输出的格式...任何帮助将不胜感激。

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]

my code starts here

我的代码从这里开始

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 

  <script src="http://maps.google.com/maps/api/js?sensor=false" 
          type="text/javascript"></script>
</head> 
<body>

    <markers>
<marker zip="17507" state="Pennsylvania" city="Bowmansville" address="1363 Bowmansville Rd." county="Lancaster" lng="-76.0134" lat="40.1957" html="Reading Equipment & Distribution (Bowmansville)">    </marker>
<marker zip="18071" state="Pennsylvania" city="Palmerton" address="1226 Little Gap Road" county="Carbon" lng="-75.617" lat="40.8083" html="SMF"></marker>
 <marker zip="18020" state="Pennsylvania" city="Bethlehem" address="2706 Brodhead Road" county="Northampton" lng="-75.3696" lat="40.6269" html="Versalift East, LLC (Specialty)"></marker>
 <marker zip="19720" state="Delaware" city="New Castle" address="203 Pigeon Point Road" county="New      Castle" lng="-75.5954" lat="39.6733" html="Auto Port, Inc."></marker>
     </markers>

   <div id="map" style="width: 500px; height: 400px;"></div>

  <script type="text/javascript">

   var locations = [];
  var iIndex=0;


    var markers = document.getElementsByTagName("marker");
     //var locations;

    for (var i = 0; i < markers.length; i++) {
          iIndex = i+1;
  }
 // String[] locations = new String[];
    locations.length = iIndex;


   for (var i = 0; i < markers.length; i++) {
     var name = markers[i].getAttribute("html");
     var address = markers[i].getAttribute("address");
     var city = markers[i].getAttribute("city");
     var state = markers[i].getAttribute("state");
     var zip = markers[i].getAttribute("zip");
      var pointlat = markers[i].getAttribute("lat");
     var pointlng = markers[i].getAttribute("lat");

     locations[i] = [];
     locations[i].length = 4;

     locations[i][0] = name;
      locations[i][1] = pointlat;
      locations[i][2] = pointlng;
     locations[i][3] = '1';

      document.write(locations);

    }



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

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

      var marker;

      for (var j = 0; j < locations.length; j++) {  



      marker = new google.maps.Marker({
         position: new google.maps.LatLng(locations[j][1], locations[j][2]),
         map: map
       });

          google.maps.event.addListener(marker, 'click', (function(marker, j) {

        return function() {
          infowindow.setContent(locations[j][0]);
          infowindow.open(map, marker);
        }
      })(marker, j));
         }


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

1 个解决方案

#1


2  

Firstly, this bit here is completely redundant:

首先,这里的这一点完全是多余的:

for (var i = 0; i < markers.length; i++) {
          iIndex = i+1;
  }
 // String[] locations = new String[];
    locations.length = iIndex;

As is this:

就是这样:

 locations[i].length = 4;

You don't have to predefine the length of an array before you populate it.

在填充数组之前,您不必预先定义数组的长度。

One issue you might be having, is that reading the values of some markup using getAttribute() will return a string. So when you try and create a marker, it expects a floating point number, not a string. So you can convert them to numerics like so:

您可能遇到的一个问题是,使用getAttribute()读取某些标记的值将返回一个字符串。因此,当您尝试创建标记时,它需要一个浮点数,而不是字符串。所以你可以将它们转换为数字,如下所示:

locations[i][1] = parseFloat(pointlat);
locations[i][2] = parseFloat(pointlng);

Also, and this is perhaps your main mistake, you're using latitude values for your longitude coordinates!

此外,这可能是您的主要错误,您正在使用经度坐标的纬度值!

 var pointlng = markers[i].getAttribute("lat");

You repeat the error when creating your map, these are the wrong way around:

您在创建地图时重复出现错误,这些方法是错误的:

center: new google.maps.LatLng(-76.0134,40.1957),

And finally, rather than looping over all your markers to populate 'locations', then looping again over 'locations' to create each marker, I think you could achieve all you need in just one loop.

最后,不是循环遍历所有标记以填充“位置”,而是再次循环“位置”以创建每个标记,我认为您可以在一个循环中实现所需的一切。

Here's a complete solution which works for me:

这是一个适合我的完整解决方案:

<!DOCTYPE html>
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
    <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>

    <script>
    function initialize() {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 8,
            center: new google.maps.LatLng(40.1957,-76.0134),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

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

        var marker;

        var location = {};

        var markers = document.getElementsByTagName("marker");

        for (var i = 0; i < markers.length; i++) {
            location = {
                name : markers[i].getAttribute("html"),
                address : markers[i].getAttribute("address"),
                city : markers[i].getAttribute("city"),
                state : markers[i].getAttribute("state"),
                zip : markers[i].getAttribute("zip"),
                pointlat : parseFloat(markers[i].getAttribute("lat")),
                pointlng : parseFloat(markers[i].getAttribute("lng"))   
            };

            console.log(location);

            marker = new google.maps.Marker({
                position: new google.maps.LatLng(location.pointlat, location.pointlng),
                map: map
            });

            google.maps.event.addListener(marker, 'click', (function(marker,location) {
                return function() {
                    infowindow.setContent(location.name);
                    infowindow.open(map, marker);
                };
            })(marker, location));
        }
    }

    google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head> 
<body>
    <markers>
        <marker zip="17507" state="Pennsylvania" city="Bowmansville" address="1363 Bowmansville Rd." county="Lancaster" lng="-76.0134" lat="40.1957" html="Reading Equipment & Distribution (Bowmansville)">    </marker>
        <marker zip="18071" state="Pennsylvania" city="Palmerton" address="1226 Little Gap Road" county="Carbon" lng="-75.617" lat="40.8083" html="SMF"></marker>
        <marker zip="18020" state="Pennsylvania" city="Bethlehem" address="2706 Brodhead Road" county="Northampton" lng="-75.3696" lat="40.6269" html="Versalift East, LLC (Specialty)"></marker>
        <marker zip="19720" state="Delaware" city="New Castle" address="203 Pigeon Point Road" county="New      Castle" lng="-75.5954" lat="39.6733" html="Auto Port, Inc."></marker>
    </markers>

    <div id="map" style="width: 500px; height: 400px;"></div>
</body>
</html>

#1


2  

Firstly, this bit here is completely redundant:

首先,这里的这一点完全是多余的:

for (var i = 0; i < markers.length; i++) {
          iIndex = i+1;
  }
 // String[] locations = new String[];
    locations.length = iIndex;

As is this:

就是这样:

 locations[i].length = 4;

You don't have to predefine the length of an array before you populate it.

在填充数组之前,您不必预先定义数组的长度。

One issue you might be having, is that reading the values of some markup using getAttribute() will return a string. So when you try and create a marker, it expects a floating point number, not a string. So you can convert them to numerics like so:

您可能遇到的一个问题是,使用getAttribute()读取某些标记的值将返回一个字符串。因此,当您尝试创建标记时,它需要一个浮点数,而不是字符串。所以你可以将它们转换为数字,如下所示:

locations[i][1] = parseFloat(pointlat);
locations[i][2] = parseFloat(pointlng);

Also, and this is perhaps your main mistake, you're using latitude values for your longitude coordinates!

此外,这可能是您的主要错误,您正在使用经度坐标的纬度值!

 var pointlng = markers[i].getAttribute("lat");

You repeat the error when creating your map, these are the wrong way around:

您在创建地图时重复出现错误,这些方法是错误的:

center: new google.maps.LatLng(-76.0134,40.1957),

And finally, rather than looping over all your markers to populate 'locations', then looping again over 'locations' to create each marker, I think you could achieve all you need in just one loop.

最后,不是循环遍历所有标记以填充“位置”,而是再次循环“位置”以创建每个标记,我认为您可以在一个循环中实现所需的一切。

Here's a complete solution which works for me:

这是一个适合我的完整解决方案:

<!DOCTYPE html>
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
    <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>

    <script>
    function initialize() {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 8,
            center: new google.maps.LatLng(40.1957,-76.0134),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

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

        var marker;

        var location = {};

        var markers = document.getElementsByTagName("marker");

        for (var i = 0; i < markers.length; i++) {
            location = {
                name : markers[i].getAttribute("html"),
                address : markers[i].getAttribute("address"),
                city : markers[i].getAttribute("city"),
                state : markers[i].getAttribute("state"),
                zip : markers[i].getAttribute("zip"),
                pointlat : parseFloat(markers[i].getAttribute("lat")),
                pointlng : parseFloat(markers[i].getAttribute("lng"))   
            };

            console.log(location);

            marker = new google.maps.Marker({
                position: new google.maps.LatLng(location.pointlat, location.pointlng),
                map: map
            });

            google.maps.event.addListener(marker, 'click', (function(marker,location) {
                return function() {
                    infowindow.setContent(location.name);
                    infowindow.open(map, marker);
                };
            })(marker, location));
        }
    }

    google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head> 
<body>
    <markers>
        <marker zip="17507" state="Pennsylvania" city="Bowmansville" address="1363 Bowmansville Rd." county="Lancaster" lng="-76.0134" lat="40.1957" html="Reading Equipment & Distribution (Bowmansville)">    </marker>
        <marker zip="18071" state="Pennsylvania" city="Palmerton" address="1226 Little Gap Road" county="Carbon" lng="-75.617" lat="40.8083" html="SMF"></marker>
        <marker zip="18020" state="Pennsylvania" city="Bethlehem" address="2706 Brodhead Road" county="Northampton" lng="-75.3696" lat="40.6269" html="Versalift East, LLC (Specialty)"></marker>
        <marker zip="19720" state="Delaware" city="New Castle" address="203 Pigeon Point Road" county="New      Castle" lng="-75.5954" lat="39.6733" html="Auto Port, Inc."></marker>
    </markers>

    <div id="map" style="width: 500px; height: 400px;"></div>
</body>
</html>