在多个边界中搜索地图坐标

时间:2014-02-14 03:50:21

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

我有一些代码要求用户提供地址并使用GoogleMaps API,返回该地址的地理编码Lat / Long。我已经设置它来查询这些坐标是否在预定的边界内。我想要做的是有多个边界,并能够搜索它们并返回结果。例如,我会有一些JSON数据或包含SW_LatLng,NE_LatLng和Answer的其他类型的数组。所以我的查询将使用以下函数,如果为true则返回答案。我的问题是如何循环多个边界并返回结果。

bounds.contains(new google.maps.LatLng(latitude,longitude));

以下是我已有的代码:

function codeAddress() {
    var bounds = new google.maps.LatLngBounds(
        new google.maps.LatLng(37,-109),
        new google.maps.LatLng(41, -102)
    );
    var geocoder = new google.maps.Geocoder();
    var address = document.getElementById('address').value;

    geocoder.geocode( { 'address': address}, function(results, status) {

      if (status == google.maps.GeocoderStatus.OK) {
        var latitude = results[0].geometry.location.lat();
        var longitude = results[0].geometry.location.lng();

      }
      var center = bounds.getCenter();
      var x = bounds.contains(new google.maps.LatLng(latitude,longitude));

      if (x) { alert('In Colorado')} else { alert('Outside Colorado')};

    });
  }

<h3>Is your Address in Colorado?</h3>
<input id="address" type="textbox" style="width:60%">
<input type="button" value="Find" onclick="codeAddress()">

我在CodePen中设置了这个(如JSFiddle)供你玩。

CodePen Link

感谢任何帮助。另外,保持数据隐藏的最佳方法是什么?

这是JSFiddle Link JSFiddle Link

1 个答案:

答案 0 :(得分:0)

您是否考虑使用多边形来定义边界?然后使用几何库中的谷歌地图api containsLocation方法(https://developers.google.com/maps/documentation/javascript/examples/poly-containsLocation)来确定点是否位于边界内?

你似乎只限于长方形区域(这可能足以满足你的目的,我不知道我只是在提出建议)。

无论哪种方式,正如你所说,你需要遍历纬度/经度边界对的数组(称之为latLngArray)。

function codeAddress() {

    var geocoder = new google.maps.Geocoder();
    var address = document.getElementById('address').value;

    geocoder.geocode( { 'address': address}, function(results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            var latitude = results[0].geometry.location.lat();
            var longitude = results[0].geometry.location.lng();

        }

        var latLngArrayLength = latLngArray.getLength();

        for (i=0; i<latLngArrayLength; i++) {
            var bounds = new google.maps.LatLngBounds(
                new google.maps.LatLng(latLngArray[i].latSW, latLngArray[i].lngSW)
                new google.maps.LatLng(latLngArray[i].latNE, latLngArray[i].lngNE)
            );

            var center = bounds.getCenter(); //what is this for??
            var x = bounds.contains(new google.maps.LatLng(latitude,longitude));

            if (x) { 
                alert('In ' + latLngArray[i].boundaryName); //not sure what you want to return exactly
                return latLngArray[i].boundaryName;
            }
        }  
    });
}