在我网站的联系页面上,可能会发生两件事:
用户启用了地理定位,地图 (
map-canvas
) 将显示从他们的位置到预定义位置的路线dest
。此功能运行良好。用户没有启用地理定位或选择不允许它。将显示一个警报(工作正常),并且一些文本将添加到
directions-panel
(工作正常)。在这种情况下,我想发生的第三件事是添加一个以map-canvas
为中心的新地图dest
,这个功能似乎不起作用,我不知道为什么。
下面的代码应该很好地表示上述内容:
<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>
任何人都知道为什么这不起作用?所有的帮助都得到了重视。
编辑:上面的工作版本