【发布时间】:2021-08-21 13:25:29
【问题描述】:
我想在谷歌地图中显示省份之间的边界。论坛里说唯一的办法就是调用openstreetmap获取坐标,然后在谷歌地图中创建一个多边形。代码失败,不显示多边形并给出“InvalidValueError:不是数组”。是因为promise call吗?还是因为,我没有很好地生成数组?
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
// TNF
zoom: 10,
center: {lat: 28.4125202, lng: -16.5566306},
mapTypeId: 'roadmap'
});
var promise = $.getJSON('https://nominatim.openstreetmap.org/details.php?place_id=256937694&polygon_geojson=1&format=json');
promise.then(function(data){
var cachedGeoJson = data; //save the geojson in case we want to update its values
console.log(JSON.stringify(cachedGeoJson)); //OUTPUT-1
console.log(cachedGeoJson.geometry.coordinates); // OUTPUT-2
for (var i = 0; i < cachedGeoJson.geometry.coordinates.length; i++) {
var coord = cachedGeoJson.geometry.coordinates[i];
coord_poligon.push(coord);
};
coord_poligon_JSON = JSON.stringify(coord_poligon);
console.log(coord_poligon_JSON ); // OUTPUT-3:
var geoObject = cachedGeoJson.geometry.coordinates;
var features = [];
features = geoObject;
var geoJson = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates":features,
},
"properties": {}
}]
};
console.log(JSON.stringify(geoJson)); // OUTPUT-4
}); // end promise.
// Construct the polygon.
triangleCoords = geoJson;
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#ea0e0e', // red color
fillOpacity: 0.20
});
bermudaTriangle.setMap(map);
//OUTPUT-1:
//{"place_id":256937694,...
//{"type":"Point","coordinates":[-16.5532956,28.4159024]},"geometry":{"type":"Polygon","coordinates":[[[-16.5705013,28.4080941],[-16.5703805,28.4076554],...
// OUTPUT-2:
//0: (2) [-16.5705013, 28.4080941]
//1: (2) [-16.5703805, 28.4076554]
//2: (2) [-16.5701851, 28.4064929]
// OUTPUT-3: [[[-16.5705013,28.4080941],[-16.5703805,28.4076554],[-16.5701851,28.4064929],...
// OUTPUT-4: {"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-16.5705013,28.4080941],[-16.5703805,28.4076554],
【问题讨论】:
标签: google-maps promise polygon openstreetmap geojson