当我致电谷歌地图指示服务时,我收到Uncaught InvalidValueError: in property origin: not a string; and not a LatLng or LatLngLiteral: not an Object
错误 - 即便如此,方向似乎已添加到地图中?
以下是在当前位置(currentPos
)和距离不太远的位置(LatLng(52.705151, -2.741861)
)之间调用路线服务的功能
function calcRoute() {
var start = currentPos;
var end = new google.maps.LatLng(52.705151, -2.741861);
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
以下是初始化地图并调用calcRoute()
函数的代码:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var currentPos;
var destinationPos;
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
directionsDisplay.setMap(map);
var infoWindow = new google.maps.InfoWindow();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
currentPos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
position: currentPos,
map: map,
title: "You are here"
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
map.setCenter(currentPos);
$.ajax({
type: 'GET',
url: $('#AddMarkersToMap').val(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
addMarkers(data, infoWindow);
},
error: function () {
alert("Error");
}
});
}, function () {
handleNoGeolocation(true);
});
} else {
handleNoGeolocation(false);
}
calcRoute();
}
一些谷歌搜索建议可能是因为地图没有加载而引起异常,所以我尝试将calcRoute
这样的调用放在一起,但没有帮助:
$(function () {
calcRoute()
});
答案 0 :(得分:1)
当您致电currentPos
时,您的calcRoute
变量未定义
getCurrentPosition
是异步的,不会在calcRoute
之前执行,因此不会设置currentPos
如果您需要在currentPos
中使用calcRoute
,则应在回调getCurrentPosition
时调用它,以确保它已定义。
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
currentPos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
position: currentPos,
map: map,
title: "You are here"
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
map.setCenter(currentPos);
$.ajax({
type: 'GET',
url: $('#AddMarkersToMap').val(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
addMarkers(data, infoWindow);
},
error: function () {
alert("Error");
}
});
calcRoute();
//\\//\\//\\
}, function () {
handleNoGeolocation(true);
});