2012-09-07 40 views
4

我有以下要求使用谷歌地圖顯示當前位置和方向API和phonegap?

從起點到目的地
  • 顯示用戶的當前位置
    1. 顯示方向。

    我正在創建一個包含路線的地圖,然後顯示用戶當前的位置。如果用戶是表示方向創建的地圖內,但如果用戶不在地圖區域的,未示出他的當前位置

    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.用戶位置適合在地圖上。有沒有一種方法可以縮小地圖以適合所有三個點,或者以三種點都可見的方式創建原始地圖。

  • 回答

    4

    添加以下後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); 
    
    相關問題