gpt4 book ai didi

javascript - 来自字符串的多边形位置?

转载 作者:行者123 更新时间:2023-11-30 12:04:26 26 4
gpt4 key购买 nike

我有一个包含多边形位置的字符串。我的问题是,我无法弄清楚如何将此字符串转换回我可以使用的 lat lng 对象,以将多边形绘制到谷歌地图上。

这是我的数据

var geometry = "(55.595892233825545, 12.663964033126831),(55.595486072831385, 12.66323447227478),(55.5953284569849, 12.665669918060303),(55.59621352237994, 12.664951086044312)"
var polygon = new google.maps.Polygon({
paths: geometry,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});

但显然,那是行不通的。我试图找到一个函数,将我的字符串转换回位置对象,但没有运气。

有什么想法吗?

最佳答案

将字符串解析为 google.maps.LatLng 对象,将它们用作 google.maps.Polygon 的路径。

var geometry = "(55.595892233825545, 12.663964033126831),(55.595486072831385, 12.66323447227478),(55.5953284569849, 12.665669918060303),(55.59621352237994, 12.664951086044312)";
// Get rid of outside ().
geometry = geometry.substring(1, geometry.length - 1);
// remove extra spaces
var coordStr = geometry.replace(/,\s/g,",");
var coordsArray = coordStr.split("),(");
var path = [];
for (var i=0; i<coordsArray.length;i++) {
var coords = coordsArray[i].split(",");
var pt = new google.maps.LatLng(
parseFloat(coords[0]),
parseFloat(coords[1]));
path.push(pt);
}
var polygon = new google.maps.Polygon({
paths: path,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});

proof of concept fiddle

代码片段:

var geocoder;
var map;

function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var geometry = "(55.595892233825545, 12.663964033126831),(55.595486072831385, 12.66323447227478),(55.5953284569849, 12.665669918060303),(55.59621352237994, 12.664951086044312)";
// Get rid of outside ().
geometry = geometry.substring(1, geometry.length - 1);
// remove extra spaces
var coordStr = geometry.replace(/,\s/g, ",");
var coordsArray = coordStr.split("),(");
var path = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < coordsArray.length; i++) {
var coords = coordsArray[i].split(",");
var pt = new google.maps.LatLng(
parseFloat(coords[0]),
parseFloat(coords[1]));
path.push(pt);
bounds.extend(pt)
}
map.fitBounds(bounds);
var polygon = new google.maps.Polygon({
paths: path,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>

关于javascript - 来自字符串的多边形位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35613350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com