如何在 Google 地图中显示存储为字符串的多边形坐标?
How to display in Google Maps polygon coordinates stored as string?
我的 MySQL 数据库中存储了一串坐标,我无法在 Google 地图中显示,因为它需要是 LatLng 对象:
'(55.46701996570562, 11.983202375732418),(55.46604683879285, 11.982086576782223),(55.465316977846335, 11.983803190551754),(55.465900867684354, 11.985863127075191)'
我知道我可以将这些坐标存储为 POLYGON 数据类型,但由于某些其他原因(与此处提及它们无关)我不想这样做。
当尝试在下面的代码中使用该坐标字符串时,它显示错误:
const polygon_coords = '(55.46701996570562, 11.983202375732418),(55.46604683879285, 11.982086576782223),(55.465316977846335, 11.983803190551754),(55.465900867684354, 11.985863127075191)';
const coords = new google.maps.Polygon({
paths: polygon_coords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
editable: true
});
错误:
InvalidValueError: at index 0: not a LatLng or LatLngLiteral with finite coordinates: not an Object
知道如何通过 Google 将坐标字符串转换为可识别的格式,例如 LatLng 或 LatLngLiteral ?
您可以像这样将您的坐标转换为 LatLng[] 坐标:
const polygon_coords = `(55.46701996570562, 11.983202375732418),
(55.46604683879285, 11.982086576782223),
(55.465316977846335, 11.983803190551754),
(55.465900867684354, 11.985863127075191)`
// Surround with [] to make an outer array.
// and replace ( and ) with [ and ] to make inner arrays
const jsonArray = `[
${polygon_coords.replace(/\)/g, ']')
.replace(/\(/g, '[')}
]`
console.log(`Your json array: \n${jsonArray}\n`)
const parsedCoords = JSON.parse(jsonArray)
console.log(`${parsedCoords}\n`)
// Assuming your coords are (lat,lng) order
const latLngs = parsedCoords.map(pair => ({lat: pair[0], lng: pair[1]}))
console.log(latLngs)
const coords = new google.maps.Polygon({
paths: latLngs,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
editable: true
});
- 将
polygon_coords
字符串解析为其单独的坐标,使用它们创建 google.maps.LatLngLiteralgoogle.maps. or
google.maps.LatLng` 对象
var polygon_coords_str = '(55.46701996570562, 11.983202375732418),(55.46604683879285, 11.982086576782223),(55.465316977846335, 11.983803190551754),(55.465900867684354, 11.985863127075191)';
polygon_coords_str = polygon_coords_str.substring(1, polygon_coords_str.length - 1);
polygon_coords_str = polygon_coords_str.split("),(");
var polygon_coords = [];
for (var i = 0; i < polygon_coords_str.length; i++) {
polygon_coords.push({ // create a google.maps.LatLngLiteral
// assume original data is (lat, lng)
lat: parseFloat(polygon_coords_str[i].split(',')[0]),
lng: parseFloat(polygon_coords_str[i].split(',')[1])
})
}
- 使用这些创建多边形:
const coords = new google.maps.Polygon({
paths: polygon_coords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
editable: true
});
代码片段:
// This example creates a simple polygon representing the Bermuda Triangle.
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 5,
center: {
lat: 55.4,
lng: 11.9
},
mapTypeId: "terrain",
});
var polygon_coords_str = '(55.46701996570562, 11.983202375732418),(55.46604683879285, 11.982086576782223),(55.465316977846335, 11.983803190551754),(55.465900867684354, 11.985863127075191)';
polygon_coords_str = polygon_coords_str.substring(1, polygon_coords_str.length - 1);
polygon_coords_str = polygon_coords_str.split("),(");
// console.log(polygon_coords_str);
var polygon_coords = [];
for (var i = 0; i < polygon_coords_str.length; i++) {
polygon_coords.push({
lat: parseFloat(polygon_coords_str[i].split(',')[0]),
lng: parseFloat(polygon_coords_str[i].split(',')[1])
})
}
console.log("polygon_coords.length=" + polygon_coords.length);
for (var i = 0; i < polygon_coords.length; i++) {
console.log(polygon_coords[i]);
}
const coords = new google.maps.Polygon({
paths: polygon_coords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
editable: true
});
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < coords.getPath().getLength(); i++)
bounds.extend(coords.getPath().getAt(i));
map.fitBounds(bounds);
coords.setMap(map);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Polygon</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly&channel=2" async></script>
</body>
</html>
我的 MySQL 数据库中存储了一串坐标,我无法在 Google 地图中显示,因为它需要是 LatLng 对象:
'(55.46701996570562, 11.983202375732418),(55.46604683879285, 11.982086576782223),(55.465316977846335, 11.983803190551754),(55.465900867684354, 11.985863127075191)'
我知道我可以将这些坐标存储为 POLYGON 数据类型,但由于某些其他原因(与此处提及它们无关)我不想这样做。
当尝试在下面的代码中使用该坐标字符串时,它显示错误:
const polygon_coords = '(55.46701996570562, 11.983202375732418),(55.46604683879285, 11.982086576782223),(55.465316977846335, 11.983803190551754),(55.465900867684354, 11.985863127075191)';
const coords = new google.maps.Polygon({
paths: polygon_coords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
editable: true
});
错误:
InvalidValueError: at index 0: not a LatLng or LatLngLiteral with finite coordinates: not an Object
知道如何通过 Google 将坐标字符串转换为可识别的格式,例如 LatLng 或 LatLngLiteral ?
您可以像这样将您的坐标转换为 LatLng[] 坐标:
const polygon_coords = `(55.46701996570562, 11.983202375732418),
(55.46604683879285, 11.982086576782223),
(55.465316977846335, 11.983803190551754),
(55.465900867684354, 11.985863127075191)`
// Surround with [] to make an outer array.
// and replace ( and ) with [ and ] to make inner arrays
const jsonArray = `[
${polygon_coords.replace(/\)/g, ']')
.replace(/\(/g, '[')}
]`
console.log(`Your json array: \n${jsonArray}\n`)
const parsedCoords = JSON.parse(jsonArray)
console.log(`${parsedCoords}\n`)
// Assuming your coords are (lat,lng) order
const latLngs = parsedCoords.map(pair => ({lat: pair[0], lng: pair[1]}))
console.log(latLngs)
const coords = new google.maps.Polygon({
paths: latLngs,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
editable: true
});
- 将
polygon_coords
字符串解析为其单独的坐标,使用它们创建google.maps.LatLngLiteralgoogle.maps. or
google.maps.LatLng` 对象
var polygon_coords_str = '(55.46701996570562, 11.983202375732418),(55.46604683879285, 11.982086576782223),(55.465316977846335, 11.983803190551754),(55.465900867684354, 11.985863127075191)';
polygon_coords_str = polygon_coords_str.substring(1, polygon_coords_str.length - 1);
polygon_coords_str = polygon_coords_str.split("),(");
var polygon_coords = [];
for (var i = 0; i < polygon_coords_str.length; i++) {
polygon_coords.push({ // create a google.maps.LatLngLiteral
// assume original data is (lat, lng)
lat: parseFloat(polygon_coords_str[i].split(',')[0]),
lng: parseFloat(polygon_coords_str[i].split(',')[1])
})
}
- 使用这些创建多边形:
const coords = new google.maps.Polygon({
paths: polygon_coords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
editable: true
});
代码片段:
// This example creates a simple polygon representing the Bermuda Triangle.
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 5,
center: {
lat: 55.4,
lng: 11.9
},
mapTypeId: "terrain",
});
var polygon_coords_str = '(55.46701996570562, 11.983202375732418),(55.46604683879285, 11.982086576782223),(55.465316977846335, 11.983803190551754),(55.465900867684354, 11.985863127075191)';
polygon_coords_str = polygon_coords_str.substring(1, polygon_coords_str.length - 1);
polygon_coords_str = polygon_coords_str.split("),(");
// console.log(polygon_coords_str);
var polygon_coords = [];
for (var i = 0; i < polygon_coords_str.length; i++) {
polygon_coords.push({
lat: parseFloat(polygon_coords_str[i].split(',')[0]),
lng: parseFloat(polygon_coords_str[i].split(',')[1])
})
}
console.log("polygon_coords.length=" + polygon_coords.length);
for (var i = 0; i < polygon_coords.length; i++) {
console.log(polygon_coords[i]);
}
const coords = new google.maps.Polygon({
paths: polygon_coords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
editable: true
});
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < coords.getPath().getLength(); i++)
bounds.extend(coords.getPath().getAt(i));
map.fitBounds(bounds);
coords.setMap(map);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Polygon</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly&channel=2" async></script>
</body>
</html>