我一直在做一个项目,在这个问题上卡了一段时间,所以现在我寻求你的帮助作为最后的手段。问题是,每当我将 markerLatLng 传递给 onclick 函数时,它就会从 LatLng 对象变为“(lat,lng)”。
我将 google.maps.LatLng() 对象分配为按钮值,然后将 this.value 传递给 onclick 函数:
service.getDetails(request, (placeDetails) => {
let markerLatLng = new google.maps.LatLng(
placeDetails.geometry.location.lat(),
placeDetails.geometry.location.lng()
);
// This logs _.Be object
console.log(markerLatLng);
infoWindow.setContent(`<p><strong>${placeDetails.name}</strong><br>
${placeDetails.formatted_address.replace(/,/g, ",<br>")}</br>
${
placeDetails.formatted_phone_number
? placeDetails.formatted_phone_number
: ""
}<br>
<button onclick="getMarkerDirections(this.value)" value="${markerLatLng}">Directions</button>
</p>`);
});
这是点击功能:
function getMarkerDirections(markerLocation) {
// This console logs "(<latitude value>, <longitude value>)"
console.log(markerLocation);
let directionsService = new google.maps.DirectionsService();
let directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
directionsService.route(
{
origin: currentCenter,
destination: markerLocation,
travelMode: "WALKING",
},
(response, status) => {
if (status === "OK") {
directionsRenderer.setDirections(response);
}
}
);
}
有什么我想念的吗?我是否以错误的方式传递了对象,或者这只是发生了什么?
我期待 onclick 函数接收 LatLng 对象,这样我就可以将它设置为方向的目的地点。我已尝试在 getMarkerDirections 中创建新的 LatLng 对象,但仍然产生相同的日志。 currentCenter 正确记录,即使它是以相同的方式创建的,唯一的区别是 markerLocation 作为参数传递。