gpt4 book ai didi

javascript - 谷歌地图 v3 : adding a new map when function 'failure' called

转载 作者:太空宇宙 更新时间:2023-11-04 15:18:19 25 4
gpt4 key购买 nike

在我网站的联系页面上可能会发生两件事:

  1. 用户启用了地理定位, map (map-canvas) 将显示从他们的位置到预定义位置 dest 的路线。此功能运行良好。

  2. 用户没有启用地理定位或选择不允许。将显示一个警报(工作正常),并且一些文本将添加到 directions-panel(工作正常)。在这种情况下,我想要发生的第三件事是将新 map 添加到以 dest 为中心的 map-canvas,此功能似乎不起作用并且我不明白为什么。

下面的代码应该很好地表示了上面的内容:

<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var dest = "Unit 20, Tallaght Business Centre, Whitestown Road, Tallaght Business Park, Ireland";//53.282882, -6.383155
var ourLocation = {lat : 53.282882, lng : -6.383155}//centre attribute of the map must be a LatLng object and not hardcoded as above

function initGeolocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition( success, failure );
}
}

//create a new map centered on user's location, display route and show directions
function success(position) {
directionsDisplay = new google.maps.DirectionsRenderer();
coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directions-panel"));
calcRoute();
}

//calculate the route from user's location to 'dest'
function calcRoute() {
var start = coords;
var end = dest;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}

//tell user geoloc isn't enabled and just plot 'ourLocation' on 'map-canvas'
function failure() {
alert("Your browser does not have geolocation enabled so we can't give you directions to our office. Enable geolocation and try again, or consult the map for our address.");
$("#directions-error-message").css({
visibility: 'visible'
});
var destMapOptions = {
zoom:13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(ourLocation.lat, ourLocation.lng)
}
map = new google.maps.Map(document.getElementById("map-canvas"), destMapOptions);
}

</script>

有人知道为什么这不起作用吗?感谢所有帮助。

编辑:上面的工作版本

最佳答案

您需要向 map 传递一个 LatLng 对象作为它的中心,而不是地址。您需要使用 Google 的 LocalSearch 服务才能完成这项工作。

var dest = {
lat : 53.282882,
lng : -6.383155
}

var destMapOptions = {
zoom:12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(dest.lat,dest.lng)
}

此外,由于您已经将 map 声明为 var,因此可以使用它而不是 map 的函数范围变量。

关于javascript - 谷歌地图 v3 : adding a new map when function 'failure' called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12282424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com