2017-03-10 64 views
-1

我試圖創建使用來自外部API http://geokey.org.uk/docs/web/project-response.html外部API數據,谷歌地圖

API響應數據谷歌地圖多邊形給出如下:

{ 
"id": 28, 
"name": "Local spots", 
"description": "", 
"isprivate": true, 
"status": "active", 
"created_at": "2014-09-15T09:40:01.747Z", 
"geographic_extent": { 
    "type": "Polygon", 
    "coordinates": [ 
     [ 
      [-0.508, 51.682], 
      [-0.53, 51.327], 
      [0.225, 51.323], 
      [0.167, 51.667], 
      [-0.508, 51.682] 
     ] 
    ] 
}, 

我如何提取geographic_extent - 座標和呈現他們在谷歌地圖上的多邊形? - 我知道它應該是一個AJAX但得到會返回一個完整的數組?

非常感謝幫助。

感謝

的腳本generaing地圖 VAR地圖;

function initMap() { 
      map = new google.maps.Map(document.getElementById('map'), { 
      zoom: 2, 
      center: new google.maps.LatLng(2.8,-187.3), 
     }); 
    } 

回答

0

要從接收到的ajax響應中提取'geographic_extent'節點,您可以使用JSON.parse函數。例如。;

var result = JSON.parse('{"id": 28,"name": "Local spots","description": "","isprivate": true,"status": "active","created_at": "2014-09-15T09:40:01.747Z","geographic_extent": {"type": "Polygon", "coordinates": [[[-0.508, 51.682],[-0.53, 51.327],[0.225, 51.323],[0.167, 51.667],[-0.508, 51.682]]]}'); 

現在你可以得到

-0.508,51.682,-0.53,51.327,0.225,51.323,0.167,51.667,-0.508,51.682 

result.geographic_extent.coordinates 

爲繪製它作爲一個多邊形,使用下面的代碼

var triangleCoords = [ 
      {lat: 25.774, lng: -80.190}, 
      {lat: 18.466, lng: -66.118}, 
      {lat: 32.321, lng: -64.757}, 
      {lat: 25.774, lng: -80.190} 
     ]; 


     var bermudaTriangle = new google.maps.Polygon({ 
      paths: triangleCoords, 
      strokeColor: '#FF0000', 
      strokeOpacity: 0.8, 
      strokeWeight: 2, 
      fillColor: '#FF0000', 
      fillOpacity: 0.35 
     }); 
     bermudaTriangle.setMap(map); 

通知的triangleCoords方式定義,它的一陣拉特, lng對象。如果您想繪製從您的ajax請求接收到的多邊形,您需要將它放入類似lat,lng對象的數組中。

http://jsbin.com/kupeyofemo/edit?html,output