谷歌地图的外部API数据

时间:2017-03-10 12:13:44

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

我正在尝试使用外部API http://geokey.org.uk/docs/web/project-response.html

中的数据在Google地图上创建多边形

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]
        ]
    ]
}, 

如何在Google地图上提取geop_extent - 坐标并将其渲染为多边形? - 我知道它应该是一个AJAX,但get get会返回一个完整的数组?

非常感谢帮助。

由于

生成地图的脚本         var map;

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

1 个答案:

答案 0 :(得分:0)

提取' geographic_extent'接收到的ajax响应节点可以使用JSON.parse函数。 e.g;

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);

注意三角形的定义方式,它是一个lat,lng对象的数组。如果要绘制从ajax请求接收的多边形,则需要将其放在lat,lng对象的类似数组中。

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