下面我有一张包含polygon with a hole in it的Google地图。
我有以下事件监听器:
google.maps.event.addListener(myPolygon.getPath(), 'insert_at', getPolygonCoords(myPolygon))
google.maps.event.addListener(myPolygon.getPath(), 'set_at', getPolygonCoords(myPolygon))
出于某种原因,当我移动任何innerCoords
时,没有任何事件触发。
如何访问在移动innerCoords时触发的事件?
const getPolygonCoords = (myPolygon) => () => {
var len = myPolygon.getPath().getLength()
let points = []
for (var i = 0; i < len; i++) {
let point = myPolygon.getPath().getAt(i).toUrlValue(5).split(',')
let lat = parseFloat(point[0])
let lng = parseFloat(point[1])
points.push({lat, lng})
}
console.log(JSON.stringify(points))
this.props.onChange(points)
}
答案 0 :(得分:2)
您需要将侦听器添加到所有路径,而不仅仅是第一个路径。
for (var i = 0; i < myPolygon.getPaths().getLength(); i++) {
google.maps.event.addListener(myPolygon.getPaths().getAt(i), 'insert_at', getPolygonCoords);
google.maps.event.addListener(myPolygon.getPaths().getAt(i), 'set_at', getPolygonCoords);
}
代码段
// This example creates a triangular polygon with a hole in it.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {
lat: 24.886,
lng: -70.268
},
});
// Define the LatLng coordinates for the polygon's outer path.
var outerCoords = [{
lat: 25.774,
lng: -80.190
}, {
lat: 18.466,
lng: -66.118
}, {
lat: 32.321,
lng: -64.757
}];
// Define the LatLng coordinates for the polygon's inner path.
// Note that the points forming the inner path are wound in the
// opposite direction to those in the outer path, to form the hole.
var innerCoords = [{
lat: 28.745,
lng: -70.579
}, {
lat: 29.570,
lng: -67.514
}, {
lat: 27.339,
lng: -66.668
}];
// Construct the polygon, including both paths.
var bermudaTriangle = new google.maps.Polygon({
paths: [outerCoords, innerCoords],
strokeColor: '#FFC107',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FFC107',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
bermudaTriangle.setEditable(true);
for (var i = 0; i < bermudaTriangle.getPaths().getLength(); i++) {
google.maps.event.addListener(bermudaTriangle.getPaths().getAt(i), 'insert_at', getPolygonCoords);
google.maps.event.addListener(bermudaTriangle.getPaths().getAt(i), 'set_at', getPolygonCoords);
}
}
function getPolygonCoords() {
console.log("getPolygonCoords");
for (var i = 0; i < this.getLength(); i++) {
console.log(this.getAt(i).toUrlValue(6));
}
}
&#13;
/* 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;
}
&#13;
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
&#13;