商店定位器 - 从邮政编码到所选商店的路线

时间:2012-10-24 12:05:11

标签: javascript google-maps google-maps-api-3 geolocation

我有一个JavaScript邮政编码搜索,根据输入的内容搜索英国的3个壁橱商店。目前它发现3家商店很好。

首先,我想在输入中输入的邮政编码中删除一个标记。

其次,当三个结果出现时,它们会在地图上标出。我想要一个名为 directions 的链接,一旦点击,就会显示从开始到所选商店的路线。

我已经尝试了以下代码,但它不起作用......但它确实从输入和方向链接获取邮政编码数据并在控制台中显示它们。我是否需要将它们转换为long和lat以使其工作?

function calcRoute() {
    var start = document.getElementById('address').value;
    var end = document.getElementById('get-directions').name;
    //console.log(start, end)
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
  }

我有这个代码作为我的开始标记,但这似乎不起作用

function initialize() {
    var start_marker = new google.maps.LatLng(document.getElementById('address').value);
    directionsDisplay = new google.maps.DirectionsRenderer();
    var mapOptions = {
      zoom:7,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: start_marker
    }
    marker = new google.maps.Marker({
          map:map,
          draggable:false,
          animation: google.maps.Animation.DROP,
          position: start_marker,
        });
    map = new google.maps.Map(document.getElementById('map'), mapOptions);
    directionsDisplay.setMap(map);
  }

此部分从邮政编码

获取长/纬度数据
this.geocode = function(address, callbackFunction) {
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var result = {};
      result.latitude = results[0].geometry.location.lat();
      result.longitude = results[0].geometry.location.lng();
      callbackFunction(result);
      //console.log(result);
        //console.log("Geocoding " + geometry.location + " OK");
        addMarker(map, results[0].geometry.location);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
      callbackFunction(null);
    }
  });

addMarker的功能在这里:

function addMarker(map, location) {

console.log("Setting marker for (location: " + location + ")");
marker = new google.maps.Marker({
map : map,
animation: google.maps.Animation.DROP,
position : location
});

}

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

google.maps.LatLng requires two floating point numbers as arguments的构造函数,而不是字符串:

var start_marker = new google.maps.LatLng(document.getElementById('address').value);

如果您拥有的只是一个地址,那么如果您想在地图上显示标记,则需要使用Geocoding service to retrieve coordinates for that address