2017-04-19 83 views
-1

如何將start = $("#from").val();,值選項更改爲用戶當前的位置?沒有輸入起始地址就更舒服了。javascript maps with google maps

任何幫助?

<script type="text/javascript"> 

     $(document).on("pageinit", "#map_page", function() { 
      initialize(); 
     }); 

     $(document).on('click', '#submit', function(e) { 
      e.preventDefault(); 
      calculateRoute(); 
     }); 

     var directionDisplay, 
      directionsService = new google.maps.DirectionsService(), 
      map; 

     function initialize() 
     { 


      directionsDisplay = new google.maps.DirectionsRenderer(); 
      directionsService = new google.maps.DirectionsService(); 
      var mapCenter = new google.maps.LatLng(51.507009, -0.170720); 

      var myOptions = { 
       zoom:16, 
       mapTypeId: google.maps.MapTypeId.ROADMAP, 
       center: mapCenter 
      } 

      map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
      directionsDisplay.setMap(map); 
      directionsDisplay.setPanel(document.getElementById("directions")); 
     } 





     function calculateRoute() 
     { 
      var selectedMode = $("#mode").val(), 
       start = $("#from").val();, 
       end = new google.maps.LatLng(51.507009, -0.170720); 
       //start = $("#from").val(); 

      if(start == '' || end == '') 
      { 
       // cannot calculate route 
       $("#results").hide(); 
       return; 
      } 
      else 
      { 
       var request = { 
        origin:start, 
        destination:end, 
        travelMode: google.maps.DirectionsTravelMode[selectedMode] 
       }; 

       directionsService.route(request, function(response, status) { 
        if (status == google.maps.DirectionsStatus.OK) { 
         directionsDisplay.setDirections(response); 
         $("#results").show(); 
         /* 
          var myRoute = response.routes[0].legs[0]; 
          for (var i = 0; i < myRoute.steps.length; i++) { 
           alert(myRoute.steps[i].instructions); 
          } 
         */ 
        } 
        else { 
         $("#results").hide(); 
        } 
       }); 

      } 
     } 
    </script> 
+0

'navigator.geolocation.getCurrentPostition(successFunc)'或'navigator.geolocation.watchPostition(successFunc)'。 ''position'帶'.coords'帶'.latitude'和'.longitude'屬性傳遞給'successFunc'。我推薦'.watchPosition',因爲用戶的瀏覽器會詢問每次調用'.getCurrentPosition'時是否可以跟蹤位置。注意一切都必須在'successFunc'內部調用,這取決於'position.coords.latitude'和'position.coords.longitude',因爲那些是異步方法。 https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition – PHPglue

+0

相關問題:[調用谷歌地圖directionsService時未捕獲的異常](http://stackoverflow.com/questions/29476953/uncaught -exception-when-calling-google-maps-directionsservice) – geocodezip

+0

相關問題:[嘗試使用流星顯示帶地理位置的Google地圖指示和用戶輸入。一切,但實際的方向工作](http://stackoverflow.com/questions/35544749/trying-to-display-google-maps-directions-with-geolocation-and-user-input-using) – geocodezip

回答

0

的解決方案是使用https和不是http爲getCurrentPosition() and watchPosition()