我如何获得谷歌地图的lat和lng?

时间:2011-08-27 11:15:00

标签: javascript google-maps-api-3

嗨我有以下代码,我想知道我是否可以获得起点和终点的纬度和长度。

这是代码

  <script type='text/javascript'>



     var rendererOptions = {
        draggable: true
      };
      var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
      var directionsService = new google.maps.DirectionsService();
      var map;
      function initialize() {
      var myOptions = {
          zoom: 7,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        directionsDisplay.setMap(map);  
        calcRoute();
      }

      function calcRoute() {
     var request = {
          origin: "Craiova, Romania",
          destination: "Bucuresti, Romania",
          travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);

          }
        });
      }

      window.onload = function() {
           initialize();
        };
    </script>

1 个答案:

答案 0 :(得分:1)

最好的方法是使用response

directionsService.route(request, function(response, status) {
    var start = response.routes[0].overview_path[0]; // Craiova
    var end = response.routes[0].overview_path.slice(-1)[0]; // Bucharest
    // start.lat(); start.lon();
    // end.lat(); end.lon();
});

另一种方法是使用地理编码器:

geo = new google.maps.Geocoder();
geo.geocode({address: "Craiova, Romania"}, function(res) {
    var location = res[0].geometry.location;
    // location.lat(); location.lon();
});