![](/img/trans.png)
[英]How to request directions from current location to destination using Google Maps JavaScript API
[英]Showing current location + directions using google maps API and phonegap?
我有以下要求
我正在創建一個帶有路線的地圖,然后在其上顯示用戶的當前位置。
function showDirection(orgn, dstntn)
{
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var map = new google.maps.Map(document.getElementById('displayMap'), {
zoom : 7,
mapTypeId : google.maps.MapTypeId.ROADMAP
});
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('displayDirections'));
var request = {
origin : orgn,
destination : dstntn,
travelMode : google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
var win = function(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat, long);
var iconimage="images/current_location_small.png";
var marker = new google.maps.Marker({
position: myLatlng,
map: map
icon: iconimage
});
marker.setMap(map);
};
var fail = function(e) {
alert('Can\'t retrieve position.\nError: ' + e);
};
var watchID = navigator.geolocation.getCurrentPosition(win, fail);
}
如果用戶位於為顯示路線而創建的地圖內,則上述代碼可以正常工作,但如果用戶不在地圖區域內,則不會顯示其當前位置。
我不知何故想要三個點1.起點,2。目的地和3.用戶位置以適應地圖。 有沒有辦法可以縮放地圖以適應所有三個點,或者以所有三個點都可見的方式創建原始地圖。
在marker.setMap(map);
之后添加以下內容marker.setMap(map);
marker.setMap(map);
//Add these lines to include all 3 points in the current viewport
var bounds = new google.maps.LatLngBounds();
bounds.extend(orgn);
bounds.extend(dstntn);
bounds.extend(myLatlng);
map.fitBounds(bounds);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.