2014-02-14 45 views
1

我有一些代碼要求用戶輸入地址並使用GoogleMaps API,返回該地址的地理編碼經緯度。我已經設置它來查詢這些座標是否落在預先確定的邊界內。我想要做的是有多重邊界,並能夠搜索並返回結果。例如,我會有一些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鏈接JSFiddle Link

+0

你在小提琴和codepen代碼被打破:'未捕獲的ReferenceError:初始化沒有定義' –

+0

我固定的jsfiddle所以現在的工作。 CodePen適合我。 – goalsquid

回答

0

你有沒有使用多邊形來定義你的界限考慮?然後在Geometry庫中使用google maps 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; 
      } 
     } 
    }); 
}