javascript 从 MySQL 数据库在 Google Maps API v3 上绘制多个多边形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23769594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:31:25  来源:igfitidea点击:

Drawing Multiple Polygons on Google Maps API v3 from MySQL database

javascriptmysqlxmlgoogle-mapsgoogle-maps-api-3

提问by nBishop

So, I am attempting to draw multiple polygons onto a google map via polygon spatial data from my MySQL table. I have a php script that outputs the following XML based off my table data.

所以,我试图通过我的 MySQL 表中的多边形空间数据将多个多边形绘制到谷歌地图上。我有一个 php 脚本,它根据我的表数据输出以下 XML。

<subdivision name="Auburn Hills">
    <coord lat="39.00748" lng="-92.323222"/>
    <coord lat="39.000843" lng="-92.323523"/>
    <coord lat="39.000509" lng="-92.311592"/>
    <coord lat="39.007513" lng="-92.311378"/>
    <coord lat="39.00748" lng="-92.323222"/>
</subdivision>
<subdivision name="Vanderveen">
    <coord lat="38.994206" lng="-92.350645"/>
    <coord lat="38.985033" lng="-92.351074"/>
    <coord lat="38.984699" lng="-92.343092"/>
    <coord lat="38.981163" lng="-92.342234"/>
    <coord lat="38.984663" lng="-92.3335"/>
    <coord lat="38.993472" lng="-92.333179"/>
    <coord lat="38.994206" lng="-92.350645"/>
</subdivision>

My issue is that the javascript I am using to try and draw each shape onto the map is returning odd coordinates. using an alert, I can see that the array that is meant to store the coordinates for the "new google.maps.Polygon" is returning the first latitude and longitude pair for each shape and drawing a line segment as opposed to the full polygon. The problematic javascript is below.

我的问题是我用来尝试在地图上绘制每个形状的 javascript 返回奇数坐标。使用警报,我可以看到用于存储“新 google.maps.Polygon”坐标的数组正在返回每个形状的第一个纬度和经度对,并绘制一条线段而不是完整的多边形。有问题的javascript如下。

function initialize() {
    var mapOptions = {
        ...
    };

    var map = new google.maps.Map(document.getElementById('map-canvas'),
  mapOptions);
    var arr = new Array();
    var polygons = [];

    downloadUrl("subdivision-coordinates.php", function(data) {
        var xml = data.responseXML;
        var subdivision = xml.documentElement.getElementsByTagName("subdivision");
        for (var i = 0; i < subdivision.length; i++) {
            var coordinates = xml.documentElement.getElementsByTagName("subdivision")[i].getElementsByTagName("coord");
            arr.push( new google.maps.LatLng(
                    parseFloat(coordinates[i].getAttribute("lat")),
                    parseFloat(coordinates[i].getAttribute("lng"))
            ));

            polygons.push(new google.maps.Polygon({
                paths: arr,
                strokeColor: '#FF0000',
                strokeOpacity: 0.8,
                strokeWeight: 2,
                fillColor: '#FF0000',
                fillOpacity: 0.35
            }));
            polygons[polygons.length-1].setMap(map);
        }
  });
}
function downloadUrl(url, callback) {
  ..blah..blah stuff from google
}
function doNothing() {}
google.maps.event.addDomListener(window, 'load', initialize);

The issue seems to be clearly related to how I am pushing the data into the array "arr". I've tried a few different methods of handling it and nothing seems to be working (I am admittedly a novice when it comes to javascript). Any advice would be greatly appreciated!

这个问题似乎与我如何将数据推送到数组“arr”中有关。我尝试了几种不同的处理方法,但似乎没有任何效果(无可否认,我是 JavaScript 的新手)。任何建议将不胜感激!

回答by geocodezip

The google.maps.Polygonpaths property takes an array of arrays of google.maps.LatLngs. You need to process through each subdivision as its own array and either push it as a separate path into the one polygon or (as below) create a new polygon for each.

所述google.maps.Polygon路径属性采用google.maps.LatLngs的数组的数组。您需要将每个细分作为其自己的数组进行处理,并将其作为单独的路径推入一个多边形中,或者(如下所示)为每个细分创建一个新的多边形。

    var subdivision = xml.getElementsByTagName("subdivision");
    for (var i = 0; i < subdivision.length; i++) {
        arr = [];
        var coordinates = xml.documentElement.getElementsByTagName("subdivision")[i].getElementsByTagName("coord");
        for (var j=0; j < coordinates.length; j++) {
          arr.push( new google.maps.LatLng(
                parseFloat(coordinates[j].getAttribute("lat")),
                parseFloat(coordinates[j].getAttribute("lng"))
          ));

          bounds.extend(arr[arr.length-1])
        }
        polygons.push(new google.maps.Polygon({
            paths: arr,
            strokeColor: '#FF0000',
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: '#FF0000',
            fillOpacity: 0.35
        }));
        polygons[polygons.length-1].setMap(map);
    }

working fiddle

工作小提琴

code snippet:

代码片段:

function initialize() {
  var mapOptions = {
    zoom: 5,
    center: new google.maps.LatLng(40, -117),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  var arr = new Array();
  var polygons = [];
  var bounds = new google.maps.LatLngBounds();

  // downloadUrl("subdivision-coordinates.php", function(data) {
  var xml = xmlParse(xmlString);
  var subdivision = xml.getElementsByTagName("subdivision");
  // alert(subdivision.length);
  for (var i = 0; i < subdivision.length; i++) {
    arr = [];
    var coordinates = xml.documentElement.getElementsByTagName("subdivision")[i].getElementsByTagName("coord");
    for (var j = 0; j < coordinates.length; j++) {
      arr.push(new google.maps.LatLng(
        parseFloat(coordinates[j].getAttribute("lat")),
        parseFloat(coordinates[j].getAttribute("lng"))
      ));

      bounds.extend(arr[arr.length - 1])
    }
    polygons.push(new google.maps.Polygon({
      paths: arr,
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35
    }));
    polygons[polygons.length - 1].setMap(map);
  }
  // });
  map.fitBounds(bounds);
}
var xmlString = '<subdivisions><subdivision name="Auburn Hills"><coord lat="39.00748" lng="-92.323222"/><coord lat="39.000843" lng="-92.323523"/><coord lat="39.000509" lng="-92.311592"/><coord lat="39.007513" lng="-92.311378"/><coord lat="39.00748" lng="-92.323222"/></subdivision><subdivision name="Vanderveen"><coord lat="38.994206" lng="-92.350645"/><coord lat="38.985033" lng="-92.351074"/><coord lat="38.984699" lng="-92.343092"/><coord lat="38.981163" lng="-92.342234"/><coord lat="38.984663" lng="-92.3335"/><coord lat="38.993472" lng="-92.333179"/><coord lat="38.994206" lng="-92.350645"/></subdivision><subdivisions>';

/**
 * Parses the given XML string and returns the parsed document in a
 * DOM data structure. This function will return an empty DOM node if
 * XML parsing is not supported in this browser.
 * @param {string} str XML string.
 * @return {Element|Document} DOM.
 */
function xmlParse(str) {
  if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
    var doc = new ActiveXObject('Microsoft.XMLDOM');
    doc.loadXML(str);
    return doc;
  }

  if (typeof DOMParser != 'undefined') {
    return (new DOMParser()).parseFromString(str, 'text/xml');
  }

  return createElement('div', null);
}

google.maps.event.addDomListener(window, 'load', initialize);
#map-canvas,
body,
html {
  height: 100%;
  width: 100%;
}
<script src="http://maps.google.com/maps/api/js"></script>
<div id="map-canvas"></div>