在这里我有一个功能route();
function route() {
// Clear any previous route boxes from the map
clearBoxes();
// Convert the distance to box around the route from miles to km
distance = parseFloat(document.getElementById("distance").value) * 1.609344;
var request = {
origin: document.getElementById("from").value,
destination: document.getElementById("to").value,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
var route = response.routes[0];
startLocation = new Object();
endLocation = new Object();
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
if (i == 0) {
startLocation.latlng = legs[i].start_location;
startLocation.address = legs[i].start_address;
}
endLocation.latlng = legs[i].end_location;
endLocation.address = legs[i].end_address;
}
}
// Make the directions request
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
// Box around the overview path of the first route
var path = result.routes[0].overview_path;
var boxes = routeBoxer.box(path, distance);
drawBoxes(boxes);
} else {
alert("Directions query failed: " + status);
}
});
}
此功能在两个地方之间创建路线方向并在地图上放置 2 个标记(起点标记和终点标记)
现在我想在其他函数中使用这个标记位置并在 console.log 中显示以查看我的代码发生了什么。
我尝试:
console.log(startLocation.latlng);
但后来我进入控制台:
ReferenceError: startLocation is not defined
get stack: function () { [native code] }
message: "startLocation is not defined"
set stack: function () { [native code] }
__proto__: Error
如何在全局变量中显示此开始和结束纬度、经度数据以在其他函数中使用?
更新:我真正需要的是使用功能 Route() 获得已经创建的标记的位置如何做到这一点:
function route() {
// Clear any previous route boxes from the map
clearBoxes();
// Convert the distance to box around the route from miles to km
distance = parseFloat(document.getElementById("distance").value) * 1.609344;
var request = {
origin: document.getElementById("from").value,
destination: document.getElementById("to").value,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
// Make the directions request
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
// Box around the overview path of the first route
var path = result.routes[0].overview_path;
var boxes = routeBoxer.box(path, distance);
drawBoxes(boxes);
} else {
alert("Directions query failed: " + status);
}
});
}