2014-03-25 23 views
0

我試圖創建從用戶當前位置到他選擇的目標的路線。問題是,我不知道如何讓用戶緯度/經度爲我的路由功能,看起來像這樣:使用MapQuest創建從用戶地理位置的路線Directions API

getRoute = function(){ 
    dir = MQ.routing.directions() 
     .on('success', function(data) { 
      //does some stuff with the routes data/directions. not important here 
     }); 

    dir.route({ 
     locations: [ 
      { latLng: { lat: USER LAT HERE, lng: USER LNG HERE } },   
      { latLng: { lat: (poiCoordinates.lat), lng: (poiCoordinates.lng) } } 
     ], 
     options: {   
      //not important as well   
     } 
    }); 

    mqroute = MQ.routing.routeLayer({ 
     directions: dir,  
    }).addTo(map); 
}; 

功能上面,當用戶選擇的興趣點,例如一個名爲餐館,然後點擊「查找路線」按鈕。我可以訪問Leaflet locate函數,但不知道如何合併它們並將用戶地理位置獲取到上面的getRoute函數中。任何建議的方式來做到這一點?乾杯!

回答

0

這爲我做:

點擊「找到我的位置到目標位置的路線按鈕」調用此函數:

createRoute = function(){ 
    if(navigator.geolocation){ 
     navigator.geolocation.getCurrentPosition(getRoute); 
    } else { 
     alert("Geolocation not supported"); 
    } 
}; 

修改後的getRoute功能看起來像這樣:

getRoute = function(position){ 

    userLatitude = position.coords.latitude; 
    userLongitude = position.coords.longitude; 

    dir = MQ.routing.directions() 
     .on('success', function(data) { 
      //does some stuff with the routes data/directions. not important here 
     }); 

    dir.route({ 
     locations: [ 
      { latLng: { lat: userLatitude, lng: userLongitude } },   
      { latLng: { lat: (poiCoordinates.lat), lng: (poiCoordinates.lng) } } 
     ], 
     options: {   
      //not important as well   
     } 
    }); 

    mqroute = MQ.routing.routeLayer({ 
     directions: dir,  
    }).addTo(map); 
}; 
1

這只是一個例子,我不知道你是否會有用。
使用地理位置可以查找傳遞給getRoute函數的用戶經度和緯度。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 
    getRoute = function(latitude,longitude){ 
     //......... 
     console.log(latitude,longitude) 
     dir.route({ 
      locations: [ 
       { latLng: { lat: latitude, lng: longitude } }, 
       { latLng: { lat: (poiCoordinates.lat), lng: (poiCoordinates.lng) } } 
      ], 
     }); 

     //....... 
    }; 
    if (navigator.geolocation) { 
     navigator.geolocation.getCurrentPosition(success,error); 
     }else{alert("Geolacion not supported")}; 

    function success(pos) { 
     var latx=pos.coords.latitude; 
     var longx=pos.coords.longitude; 
     getRoute(latx,longx) 
    }; 
    function error(pos) { 
    alert('error') 
    };   
}); 
</script> 
相關問題