我对javascript的了解不是很好,所以我不确定如何从同一个事件监听器加载第二个函数。
var tutsImg = "houseProxy.jpg";
var kingTuts = new google.maps.LatLng(55.86256, -4.265);
var tutsDisplay = new google.maps.Marker({
position: kingTuts,
map: map,
icon: tutsImg,
title:"King Tut's Wah Wah Hut"
});
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h2 id="firstHeading" class="firstHeading">King Tuts Wah Wah Hut</h2>'+
'<div id="bodyContent">'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
// Creating directions
function calcRoute () {
var request = {
origin: 'Glasgow',
destination: kingTuts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addListener(tutsDisplay, 'click', function() {
infowindow.open(map,tutsDisplay);
calcRoute();
});
所以在这里我创建变量以在我选择的建筑物的位置上显示自定义标记。但我也想调用计算和显示从用户当前位置到点击图标位置的方向的功能。
任何帮助人员?
答案 0 :(得分:0)
我无法完全理解这是什么问题。 但我编写的代码将从用户位置显示方向 到点击地图的位置。为了获取用户位置,我使用地理位置API(HTML5)。
我希望这可以帮助你:)
(function(global) {
var google = global.google;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay;
// initialize google map
var initialize = function() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// initialize map
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay.setMap(map);
// add event on map click
// @param {Object} event The custom map event object
// which contain latitude and langitude
google.maps.event.addListener(map, 'click', function(event) {
// getUserPosition is async function
// because it require user permission
getUserPosition(calcRoute.bind(global, event.latLng));
});
};
// html 5 geolocation API
// Get user position
var getUserPosition = function(callback) {
global.navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var langitude = position.coords.longitude;
// convert user position to google.maps
// LatLng object
var origin = new google.maps.LatLng(latitude, langitude);
callback(origin);
} /*, onError */ );
};
// calc direction from user location
// to position clicked on map
var calcRoute = function(distPosition, originPosition) {
var request = {
origin: originPosition,
destination: distPosition,
travelMode: google.maps.TravelMode.DRIVING // it's work onliy for one continent
};
directionsService.route(request, function(result, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
};
// events
google.maps.event.addDomListener(window, 'load', initialize);
}(this));
上的链接