获取谷歌地图中已创建标记的位置(lat,lng)

时间:2013-09-19 13:13:58

标签: javascript jquery function google-maps methods

这里我有一个功能路线();这个函数在两个地方之间创建一个方向,从startPoint和endPoint创建两个标记。一切都还可以,但是我怎么能在这里编写一个函数,它将从起点返回lat,lng,从终点返回lng而不使用地理编码,因为已经在此函数中创建了标记

FUNCTION route();代码:

function route() {
  // Clear any previous route boxes from the map
  clearBoxes();

  // Convert the distance to box around the route from miles to km
  distance = parseFloat(document.getElementById("distance").value) * 1.609344;

  var request = {
    origin: document.getElementById("from").value,
    destination: document.getElementById("to").value,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  }

  // Make the directions request
  directionService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsRenderer.setDirections(result);

      // Box around the overview path of the first route
      var path = result.routes[0].overview_path;
      var boxes = routeBoxer.box(path, distance);
      // alert(boxes.length);
      drawBoxes(boxes);
      findPlaces(boxes,0);
    } else {
      alert("Directions query failed: " + status);
    }
  });
}

所以我需要一些变量等.var startPoint = [lat,lng]; var endPoint = [lat,lng]来到这里因为我不想再次使用地理编码请求,因为这里是标记,他的坐标位置已经创建...

我想获得两个标记的位置以及我如何做到这一点?

1 个答案:

答案 0 :(得分:2)

将位置解析出DirectionsResult

if (status == google.maps.DirectionsStatus.OK) {
  directionsRenderer.setDirections(result);
  var route = response.routes[0];
  startLocation = new Object();
  endLocation = new Object();

  var path = response.routes[0].overview_path;
  var legs = response.routes[0].legs;
  for (i=0;i<legs.length;i++) {
    if (i == 0) { 
      startLocation.latlng = legs[i].start_location;
      startLocation.address = legs[i].start_address;
    }
    endLocation.latlng = legs[i].end_location;
    endLocation.address = legs[i].end_address;
  }
  // ... rest of your code to display the route ...

working example that does that (and renders the polyline and creates markers)