谷歌Api地图与方向使用JavaScript

时间:2011-10-12 14:40:52

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

  (function(){
window.onload =function(){
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();

directionsDisplay = new google.maps.DirectionsRenderer();
    document.getElementById("lat").style.visibility = "hidden";
    document.getElementById("longi").style.visibility = "hidden";
    document.getElementById("number").style.visibility = "hidden";
    document.getElementById("addressone").style.visibility = "hidden";
    document.getElementById("city").style.visibility = "hidden";
    document.getElementById("countie").style.visibility = "hidden";
    document.getElementById("postcode").style.visibility = "hidden";
    var mapDiv = document.getElementById('map');
    var latitude = document.frmOne.lat.value;
    var longitude = document.frmOne.longi.value;
    var number = document.frmOne.number.value;
    var addressone = document.frmOne.addressone.value;
    var city = document.frmOne.city.value;
    var countie = document.frmOne.countie.value;
    var postcode = document.frmOne.postcode.value;
    var latlng = new google.maps.LatLng(latitude,longitude);
    var options ={
        center:latlng,
        zoom:18,
        mapTypeId:google.maps.MapTypeId.ROADMAP

    };

    var map= new google.maps.Map(document.getElementById('map'),options);
     directionsDisplay.setMap(map);

      var marker = new google.maps.Marker({
    position: new google.maps.LatLng(latitude,longitude),
  map: map,
  title: 'Click me'
   });

    var infowindow = new google.maps.InfoWindow({
  content: number+" "+addressone+"<br>"+city+"<br>"+countie+"<br>"+postcode
   });

    google.maps.event.addListener(marker, 'click', function() {
  // Calling the open method of the infoWindow
  infowindow.open(map, marker);
});


 var start = (latitude,longitude);
 var end = "51.403650,-1.323252";
 var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
  };
    directionsService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
  directionsDisplay.setDirections(result);
    }
    });



    };
   })();

使用php生成经度和纬度并且工作完美。地图加载包括标记,但方向不显示。

我找不到一个很好的指导教程,所以如果有人知道这也是一个帮助 我知道我的代码不是很整洁,但我对java脚本不是很了解。

1 个答案:

答案 0 :(得分:5)

你已经复制了它看起来像我example from their own reference,这很好。但是他们正在使用地名,而你正在使用latlng坐标。你需要做的是使用实际的latlng对象,而不仅仅是“51.403650,-1.323252”(纬度,经度)

var request = {
  origin:new google.maps.LatLng(latitude,longitude),
  destination:new google.maps.LatLng(51.403650,-1.323252),
  travelMode: google.maps.TravelMode.DRIVING
};