Google Maps API路线 - 移动路线链接至边栏 [英] Google Maps API Directions - Move directions link to sidebar

查看:155
本文介绍了Google Maps API路线 - 移动路线链接至边栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,当您点击某个标记时,可点击的获取路线链接随标题和地址一起显示。我还希望获取路线链接也出现在侧栏上。

 <!DOCTYPE html> 
< html>
< head>
< title> Google Maps JavaScript API v3示例:Map Simple< / title>
< meta name =viewportcontent =width = device-width,initial-scale = 1.0,user-scalable = no>
< meta charset =utf-8>
< style>
html,body,#map_canvas {
margin:0;
padding:0;
身高:100%;
}
< / style>

< style type ='text / css'>
.text
{
width:300px;
height:600px;
背景颜色:白色;
overflow:scroll;
overflow-x:hidden;
}
< / style>

< script src =https://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false>< / script>
< script type =text / javascript>

//商店名称[0],地址[1],坐标[2],图标[3]

var locations = [
[John Doe ,145 Rock Ridge Road,Chester,NY,41.314926,-74.270134,http://maps.google.com/mapfiles/ms/icons/blue.png],
[Jim Smith,12 Williams Rd,Montvale,NJ,41.041599,-74.019554,http://maps.google.com/mapfiles/ms/icons/green.png],
[John 琼斯,新泽西州华盛顿市689 Fern St小镇,40.997704,-74.050598,http://maps.google.com/mapfiles/ms/icons/yellow.png],

];
// alert(locations.length);

var geocoder = null;
var map = null;
var customerMarker = null;
var gmarkers = [];
var closest = [];
var directionsDisplay = new google.maps.DirectionsRenderer();;
var directionsService = new google.maps.DirectionsService();
var map;

函数initialize(){
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'),
{
zoom:9,
center:new google.maps.LatLng(52.6699927, -0.7274620),
mapTypeId:google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker,i;
var bounds = new google.maps.LatLngBounds();
document.getElementById('info')。innerHTML =found+ locations.length +locations< br>;
for(i = 0; i< locations.length; i ++){
var coordStr = locations [i] [2];
var coords = coordStr.split(,);
var pt = new google.maps.LatLng(parseFloat(coords [0]),parseFloat(coords [1]));
bounds.extend(pt);
marker = new google.maps.Marker({
position:pt,
map:map,
icon:locations [i] [3],
address:位置[i] [1],
title:locations [i] [0],
** html:locations [i] [0] +< br>+ locations [i] [ 1] +< br>< br>< a href ='javascript:getDirections(customerMarker.getPosition(),& quot;+ locations [i] [1] +& quot;);' >获取路线< / a>**
});
gmarkers.push(marker);
google.maps.event.addListener(marker,'click',(function(marker,i){return function()
{infowindow.setContent(marker.html);
infowindow。打开(地图,标记);
}
})
(marker,i));
}
map.fitBounds(bounds);


$ b函数codeAddress(){
var address = document.getElementById('address')。value;
geocoder.geocode({'address':address},function(results,status){
if(status == google.maps.GeocoderStatus.OK){
map.setCenter(results (0).geometry.location);
if(customerMarker)customerMarker.setMap(null);
customerMarker = new google.maps.Marker({
map:map,
position:results [0] .geometry.location
});
nearest = findClosestN(results [0] .geometry.location,12);
//开车距离
最接近= nearest.splice(0,12);
calculateDistances(结果[0] .geometry.location,最接近12);
} else {
alert('Geocode was not successful for原因如下:'+ status';
}
});
}

函数findClosestN(pt,numberOfResults){
var closest = [];
document.getElementById('info')。innerHTML + =processing+ gmarkers.length +< br>;
for(var i = 0; i gmarkers [i] .distance = google.maps.geometry.spherical.computeDistanceBetween(pt,gmarkers [i] .getPosition( ));
document.getElementById('info')。innerHTML + =process+ i +:+ gmarkers [i] .getPosition()。toUrlValue(6)+:+ gmarkers [i] .distance。 toFixed(2)+ <峰; br> 中;
gmarkers [i] .setMap(null);
closest.push(gmarkers [i]);
closest.sort(sortByDist);
}

返回最近;


函数sortByDist(a,b){
return(a.distance- b.distance)

}

函数calculateDistances(pt,closest,numberOfResults){
var service = new google.maps.DistanceMatrixService();
var request = {
origins:[pt],
destinations:[],
travelMode:google.maps.TravelMode.DRIVING,
unitSystem:google.maps .UnitSystem.IMPERIAL,
avoidHighways:false,
avoidTolls:false
};
for(var i = 0; i< closest.length; i ++){
request.destinations.push(closest [i] .getPosition());

service.getDistanceMatrix(request,function(response,status){
if(status!= google.maps.DistanceMatrixStatus.OK){
alert('Error was: '+ status');
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('side_bar');
outputDiv.innerHTML ='';

var results = response.rows [0] .elements;
//将标题和地址保存在记录中以便分类
for (var i = 0; i< closest.length; i ++){
results [i] .title = closest [i] .title;
results [i] .address = closest [i]。 address;
results [i] .idx_closestMark = i;
}
results.sort(sortByDistDM);
for(var i = 0;
((i< ; numberOfResults)&&& amp;(i< closest.length)); i ++){
nearest [i] .setMap(map);

** outputDiv.innerHTML + = <一个href ='javascript:google.maps.event.trigger(closest [+ results [i] .idx_closestMark +],\click \);'>+ results [i] .title +'< ; / a>< br>'+ results [i] .address +< br>+ results [i] .distance.text +'about'+ results [i] .duration.text +< br> ;< a href ='javascript:getDirections(customerMarker.getPosition(),& quot;+ locations [i] [1] +& quot;);'>获取路线< / a>< br> ;< hr>**
}
}
});
}

函数getDirections(origin,destination){
var request = {
origin:origin,
destination:destination,
travelMode :google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request,function(response,status){
if(status == google.maps.DirectionsStatus.OK){
directionsDisplay.setMap(map);
directionsDisplay.setDirections(response);
directionsDisplay.setPanel(document.getElementById('side_bar'));
}
});
}

函数sortByDistDM(a,b){
return(a.distance.value - b.distance.value)
}

google.maps.event.addDomListener(window,'load',initialize);
< / script>
< / head>
< body>
< table border =0>< tr>< td>
< div id =mapstyle =height:600px; width:800px;>< / div>
< / td>< td>
< div id =side_barclass ='text'> < / DIV>
< / td>< / tr>< / table>

< input id =addresstype =textvalue =Palo Alto,CA>< / input>
< input type =buttonvalue =Searchonclick =codeAddress();>< / input>
< div id =info>< / div>

< / body>
< / html>

我试图从这里搬离:

<$ [+]< br>< br>< a href =' javascript:getDirections(customerMarker.getPosition(),& quot;+ locations [i] [1] +& quot;);'>获取路线< / a>

到这里:

  outputDiv.innerHTML + =< a href ='javascript:google.maps.event.trigger(closest [+ results [i] .idx_closestMark +],\click \) ;'>中+ results [i] .title +'< / a>< br>'+ results [i] .address +< br> + results [i] .distance.text +'about'+ results [i] .duration.text +< br>< a href ='javascript:getDirections(customerMarker.getPosition(),& quot;位置[i] [1] +& quot;);'>获取路线< / a>< br>< hr> 

我现在可以在侧边栏中显示获取路线链接, t匹配正确的标题和地址就像他们从标记做的一样。任何人都知道如何解决这个问题?

解决方案

您需要使用已排序版本的地址,而不是版本输入。

  //将标题和地址保存在记录中用于排序
for(var i = 0; i< nearest.length; i ++){
results [i] .title = closest [i] .title;
results [i] .address = closest [i] .address;
results [i] .idx_closestMark = i;
}
results.sort(sortByDistDM);
//将输出中存储的值用于边栏
for(var i = 0;
((i nearest [i] .setMap(map);
outputDiv.innerHTML + =< a href ='javascript:google.maps.event.trigger(closest [+ results [i] .idx_closestMark +],\click \);' >中+ results [i] .title +'< / a>< br>'+ results [i] .address +< br> + results [i] .distance.text +'about'+ results [i] .duration.text +< br>< a href ='javascript:getDirections(customerMarker.getPosition(),& quot; results [i] .address +& quot;);'>获取路线< / a>< br>< hr>

$ / code>

排序功能:

 函数sortByDistDM(a,b){
return(a.distance.value - b.distance.value)
}

概念验证小提琴



代码段:

var locations = [[John Doe,145 Rock Ridge Road,Chester,NY,41.314926,-74.270134,http://maps.google.com/mapfiles/ms/icons/blue.png ],[Jim Smith,12 Williams Rd,Montvale,NJ,41.041599,-74.019554,http://maps.google.com/mapfiles/ms/icons/green.png],[ John Jones,689 Fern St Township of Washington,NJ,40.997704,-74.050598,http://maps.google.com/mapfiles/ms/icons/yellow.png\"],]; alert (locations.length); var geocoder = null; var map = null; var custome rMarker = null; var gmarkers = []; var closest = []; var directionsDisplay = new google.maps.DirectionsRenderer();; var directionsService = new google.maps.DirectionsService(); var map; function initialize(){/ / alert(init); geocoder = new google.maps.Geocoder(); map = new google.maps.Map(document.getElementById('map'),{zoom:9,center:new google.maps.LatLng(52.6699927,-0.7274620),mapTypeId:google.maps.MapTypeId.ROADMAP}); var infowindow = new google.maps.InfoWindow(); var marker,i; var bounds = new google.maps.LatLngBounds(); document.getElementById('info')。innerHTML =found+ locations.length +locations< br>; for(i = 0; i< locations.length; i ++){var coordStr = locations [i] [2]; var coords = coordStr.split(,); var pt = new google.maps.LatLng(parseFloat(coords [0]),parseFloat(coords [1])); bounds.extend(PT); marker = new google.maps.Marker({position:pt,map:map,icon:locations [i] [3],address:locations [i] [1],title:locations [i] [0],html:位置[i] [0] +< br>+ locations [i] [1] +< br>< br>< a href ='javascript:getDirections(customerMarker.getPosition() + locations [i] [1] +& quot;);'>获取路线< / a>}); gmarkers.push(标记); google.maps.event.addListener(marker,'click',(function(marker,i){return function(){infowindow.setContent(marker.html); infowindow.open(map,marker);}})(marker , 一世)); } map.fitBounds(bounds);} function codeAddress(){var address = document.getElementById('address')。value; geocoder.geocode({'address':address},function(results,status){if(status == google.maps.GeocoderStatus.OK){map.setCenter(results [0] .geometry.location); if(customerMarker )customerMarker.setMap(null); customerMarker = new google.maps.Marker({map:map,position:results [0] .geometry.location}); nearest = findClosestN(results [0] .geometry.location,12) ; //获取驾驶距离nearest = nearest.splice(0,12); calculateDistances(results [0] .geometry.location,nearest,12);} else {alert('Geocode由于以下原因不成功:'+状态);}});}函数findClosestN(pt,numberOfResults){var closest = []; document.getElementById('info')。innerHTML + =processing+ gmarkers.length +< br>; for(var i = 0; i

html,body,#map_canvas {margin:0;填充:0; height:100%;} table,tr,td {height:100%; } .text {width:300px;身高:500px;背景颜色:白色;溢出:滚动; overflow-x:hidden;} < script src = https://maps.googleapis.com/maps/api/js?libraries=geometry\"> ;</script><table border =0> < TR> < TD> < div id =mapstyle =height:100%; width:400px;>< / div> < / TD> < TD> < div id =side_barclass ='text'> < / DIV> < / TD> < / table>< input id =addresstype =textvalue =Paramus,NJ/>< input type =buttonvalue =Searchonclick =codeAddress (); />< div id =info>< / div>

Currently when you click on a marker, a clickable get directions link comes up along with title and address. I would also like the get directions link to appear on the sidebar as well.

<!DOCTYPE html>
 <html>
   <head>
     <title>Google Maps JavaScript API v3 Example: Map Simple</title>
     <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
     <meta charset="utf-8">
     <style>
       html, body, #map_canvas {
         margin: 0;
         padding: 0;
         height: 100%;
         }
     </style>

<style type='text/css'>
.text
{
width:300px;
height:600px;
background-color:white;
overflow:scroll;
overflow-x: hidden;
}
</style>

<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script type="text/javascript">     

// Store Name[0],Address[1],Coordinates[2],Icon[3]

var locations = [
  ["John Doe", "145 Rock Ridge Road, Chester, NY ", "41.314926,-74.270134", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
  ["Jim Smith", "12 Williams Rd, Montvale, NJ ", "41.041599,-74.019554", "http://maps.google.com/mapfiles/ms/icons/green.png"],
  ["John Jones", "689 Fern St Township of Washington, NJ ", "40.997704,-74.050598", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],

 ];
// alert(locations.length);

var geocoder = null;
var map = null;
var customerMarker = null;
var gmarkers = [];
var closest = [];
var directionsDisplay = new google.maps.DirectionsRenderer();;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  geocoder = new google.maps.Geocoder();
  map = new google.maps.Map(document.getElementById('map'), 
        {       
            zoom: 9,       
            center: new google.maps.LatLng(52.6699927, -0.7274620),       
            mapTypeId: google.maps.MapTypeId.ROADMAP     
        });      
  var infowindow = new google.maps.InfoWindow();      
  var marker, i;      
  var bounds = new google.maps.LatLngBounds();
  document.getElementById('info').innerHTML = "found "+locations.length+" locations<br>";
  for (i = 0; i < locations.length; i++) {         
            var coordStr = locations[i][2];
        var coords = coordStr.split(",");
        var pt = new google.maps.LatLng(parseFloat(coords[0]),parseFloat(coords[1]));
            bounds.extend(pt);
            marker = new google.maps.Marker({         
                            position: pt,         
                            map: map,
                icon: locations[i][3],
                            address: locations[i][1],
                            title: locations[i][0],
                            **html: locations[i][0]+"<br>"+locations[i][1]+"<br><br><a href='javascript:getDirections(customerMarker.getPosition(),&quot;"+locations[i][1]+"&quot;);'>Get Directions</a>"**
                            });                              
            gmarkers.push(marker);
            google.maps.event.addListener(marker, 'click', (function(marker, i) {         return function() 
            {           infowindow.setContent(marker.html);
                        infowindow.open(map, marker);         
            }       
        })
        (marker, i));     
    }
    map.fitBounds(bounds);   

}

      function codeAddress() {
        var address = document.getElementById('address').value;
        geocoder.geocode( { 'address': address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
        if (customerMarker) customerMarker.setMap(null);
            customerMarker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
        closest = findClosestN(results[0].geometry.location,12);
            // get driving distance
            closest = closest.splice(0,12);
            calculateDistances(results[0].geometry.location, closest,12);
          } else {
            alert('Geocode was not successful for the following reason: ' + status);
          }
        });
      }

function findClosestN(pt,numberOfResults) {
   var closest = [];
   document.getElementById('info').innerHTML += "processing "+gmarkers.length+"<br>";
   for (var i=0; i<gmarkers.length;i++) {
     gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt,gmarkers[i].getPosition());
     document.getElementById('info').innerHTML += "process "+i+":"+gmarkers[i].getPosition().toUrlValue(6)+":"+gmarkers[i].distance.toFixed(2)+"<br>";
     gmarkers[i].setMap(null);
     closest.push(gmarkers[i]);
     closest.sort(sortByDist);  
   }

   return closest;
}

function sortByDist(a,b) { 
 return (a.distance- b.distance)

}

function calculateDistances(pt,closest,numberOfResults) {
  var service = new google.maps.DistanceMatrixService();
  var request =    {
      origins: [pt],
      destinations: [],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.IMPERIAL,
      avoidHighways: false,
      avoidTolls: false
    };
  for (var i=0; i < closest.length; i++) {
  request.destinations.push(closest[i].getPosition());
  }
  service.getDistanceMatrix(request, function (response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
      alert('Error was: ' + status);
    } else {
      var origins = response.originAddresses;
      var destinations = response.destinationAddresses;
      var outputDiv = document.getElementById('side_bar');
      outputDiv.innerHTML = '';

     var results = response.rows[0].elements;
      // save title and address in record for sorting
      for (var i = 0; i < closest.length; i++) {
        results[i].title = closest[i].title;
        results[i].address = closest[i].address;
        results[i].idx_closestMark = i;
      }
      results.sort(sortByDistDM);
      for (var i = 0;
        ((i < numberOfResults) && (i < closest.length)); i++) {
        closest[i].setMap(map);

        **outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),&quot;"+locations[i][1]+"&quot;);'>Get Directions</a><br><hr>"**
      }
    }
  });
}

function getDirections(origin, destination) {
  var request = {
      origin:origin,
      destination:destination,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setMap(map);
      directionsDisplay.setDirections(response);
      directionsDisplay.setPanel(document.getElementById('side_bar'));
    }
  });
}

function sortByDistDM(a, b) {
  return (a.distance.value - b.distance.value)
}

google.maps.event.addDomListener(window, 'load', initialize);
</script> 
   </head>
   <body>
   <table border="0"><tr><td>
     <div id="map" style="height: 600px; width:800px;"></div>
     </td><td>
     <div id="side_bar" class = 'text'> </div>
     </td></tr></table>

<input id="address" type="text" value="Palo Alto, CA"></input>
<input type="button" value="Search" onclick="codeAddress();"></input>
<div id="info"></div>

   </body>
 </html>

I tried to move from here:

html: locations[i][0]+"<br>"+locations[i][1]+"<br><br><a href='javascript:getDirections(customerMarker.getPosition(),&quot;"+locations[i][1]+"&quot;);'>Get Directions</a>"

to here:

outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),&quot;"+locations[i][1]+"&quot;);'>Get Directions</a><br><hr>"

I'm now able to have the get directions link appear in the sidebar, however the directions don't match up to correct title and address like they do from the marker. Anyone know how to fix this?

解决方案

You need to use the "sorted" version of the address, not the version in the input.

// save title and address in record for sorting
for (var i = 0; i < closest.length; i++) {
  results[i].title = closest[i].title;
  results[i].address = closest[i].address;
  results[i].idx_closestMark = i;
}
results.sort(sortByDistDM);
// use the stored values in the output to the sidebar
for (var i = 0;
  ((i < numberOfResults) && (i < closest.length)); i++) {
  closest[i].setMap(map);
  outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),&quot;" + results[i].address + "&quot;);'>Get Directions</a><br><hr>"
}

sort function:

function sortByDistDM(a, b) {
  return (a.distance.value - b.distance.value)
}

proof of concept fiddle

code snippet:

var locations = [
  ["John Doe", "145 Rock Ridge Road, Chester, NY ", "41.314926,-74.270134", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
  ["Jim Smith", "12 Williams Rd, Montvale, NJ ", "41.041599,-74.019554", "http://maps.google.com/mapfiles/ms/icons/green.png"],
  ["John Jones", "689 Fern St Township of Washington, NJ ", "40.997704,-74.050598", "http://maps.google.com/mapfiles/ms/icons/yellow.png"],

];
// alert(locations.length);

var geocoder = null;
var map = null;
var customerMarker = null;
var gmarkers = [];
var closest = [];
var directionsDisplay = new google.maps.DirectionsRenderer();;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  // alert("init");
  geocoder = new google.maps.Geocoder();
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 9,
    center: new google.maps.LatLng(52.6699927, -0.7274620),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var infowindow = new google.maps.InfoWindow();
  var marker, i;
  var bounds = new google.maps.LatLngBounds();
  document.getElementById('info').innerHTML = "found " + locations.length + " locations<br>";
  for (i = 0; i < locations.length; i++) {
    var coordStr = locations[i][2];
    var coords = coordStr.split(",");
    var pt = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
    bounds.extend(pt);
    marker = new google.maps.Marker({
      position: pt,
      map: map,
      icon: locations[i][3],
      address: locations[i][1],
      title: locations[i][0],
      html: locations[i][0] + "<br>" + locations[i][1] + "<br><br><a href='javascript:getDirections(customerMarker.getPosition(),&quot;" + locations[i][1] + "&quot;);'>Get Directions</a>"
    });
    gmarkers.push(marker);
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(marker.html);
          infowindow.open(map, marker);
        }
      })
      (marker, i));
  }
  map.fitBounds(bounds);

}

function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      if (customerMarker) customerMarker.setMap(null);
      customerMarker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location
      });
      closest = findClosestN(results[0].geometry.location, 12);
      // get driving distance
      closest = closest.splice(0, 12);
      calculateDistances(results[0].geometry.location, closest, 12);
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

function findClosestN(pt, numberOfResults) {
  var closest = [];
  document.getElementById('info').innerHTML += "processing " + gmarkers.length + "<br>";
  for (var i = 0; i < gmarkers.length; i++) {
    gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt, gmarkers[i].getPosition());
    document.getElementById('info').innerHTML += "process " + i + ":" + gmarkers[i].getPosition().toUrlValue(6) + ":" + gmarkers[i].distance.toFixed(2) + "<br>";
    gmarkers[i].setMap(null);
    closest.push(gmarkers[i]);
    closest.sort(sortByDist);
  }

  return closest;
}

function sortByDist(a, b) {
  return (a.distance - b.distance)

}

function calculateDistances(pt, closest, numberOfResults) {
  var service = new google.maps.DistanceMatrixService();
  var request = {
    origins: [pt],
    destinations: [],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.IMPERIAL,
    avoidHighways: false,
    avoidTolls: false
  };
  for (var i = 0; i < closest.length; i++) {
    request.destinations.push(closest[i].getPosition());
  }
  service.getDistanceMatrix(request, function(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
      alert('Error was: ' + status);
    } else {
      var origins = response.originAddresses;
      var destinations = response.destinationAddresses;
      var outputDiv = document.getElementById('side_bar');
      outputDiv.innerHTML = '';

      var results = response.rows[0].elements;
      // save title and address in record for sorting
      for (var i = 0; i < closest.length; i++) {
        results[i].title = closest[i].title;
        results[i].address = closest[i].address;
        results[i].idx_closestMark = i;
      }
      results.sort(sortByDistDM);
      for (var i = 0;
        ((i < numberOfResults) && (i < closest.length)); i++) {
        closest[i].setMap(map);

        outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest[" + results[i].idx_closestMark + "],\"click\");'>" + results[i].title + '</a><br>' + results[i].address + "<br>" + results[i].distance.text + ' approximately ' + results[i].duration.text + "<br><a href='javascript:getDirections(customerMarker.getPosition(),&quot;" + results[i].address + "&quot;);'>Get Directions</a><br><hr>"

      }
    }
  });
}

function getDirections(origin, destination) {
  var request = {
    origin: origin,
    destination: destination,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setMap(map);
      directionsDisplay.setDirections(response);
      directionsDisplay.setPanel(document.getElementById('side_bar'));
    }
  });
}

function sortByDistDM(a, b) {
  return (a.distance.value - b.distance.value)
}

google.maps.event.addDomListener(window, 'load', initialize);

html,
body,
#map_canvas {
  margin: 0;
  padding: 0;
  height: 100%;
}
table,tr,td {
  height: 100%;
  }


.text {
  width: 300px;
  height: 500px;
  background-color: white;
  overflow: scroll;
  overflow-x: hidden;
}

<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<table border="0">
  <tr>
    <td>
      <div id="map" style="height: 100%; width:400px;"></div>
    </td>
    <td>
      <div id="side_bar" class='text'> </div>
    </td>
  </tr>
</table>

<input id="address" type="text" value="Paramus, NJ" />
<input type="button" value="Search" onclick="codeAddress();" />
<div id="info"></div>

这篇关于Google Maps API路线 - 移动路线链接至边栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆