使用Google Maps API指示标记的方向 [英] Directions to marker with Google Maps API

查看:142
本文介绍了使用Google Maps API指示标记的方向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我使用Google Maps API,目前我有一个自定义标记来突出显示位置。如果可能的话,我想要做的是能够点击它并使其显示谷歌地图方向对话框(例如 THIS ),通常在Google地图上点击地点名称即可。在这一刻我只是放大了标记,但显然我只是摆脱这个功能,如果我能得到这个工作。



以下是我的代码:

 < script type =text / javascriptsrc =http://maps.google.com/maps/api/js?sensor=false>< / script> 
< script type =text / javascript>
函数initialize(){

var location = new google.maps.LatLng(50.871622,-4.131561);

var mapOptions = {
center:location,
zoom:11,
scrollwheel:false
};

var map = new google.maps.Map(document.getElementById(map),
mapOptions);

var image = {
url:'img / mapmarker.png',
};
var marker = new google.maps.Marker({
position:location,
map:map,
animation:google.maps.Animation.DROP,
icon :image,
title:'鹿园乳业'
});
google.maps.event.addListener(marker,'click',function(){
map.setZoom(15);
map.setCenter(marker.getPosition());
});

}

google.maps.event.addDomListener(window,'load',initialize);
< / script>


解决方案

http://www.geocodezip.com/v3_MW_example_map4c.html\">这个例子。最初的功能是由 Mike Williams为Google Maps Javascript API v2 撰写的(现在已被弃用和关闭) 。所以这个Javascript是基于社区教会Javascript团队提供的代码( http://www.bisphamchurch.org.uk/ http://econym.org.uk/gmap/



工作代码片段:



var directionsDisplay = new google.maps.DirectionsRenderer(); var directionsService = new google.maps.DirectionsService() ; //数组保存side_bar使用的标记和html的副本//因为函数的关闭技巧在这里不起作用var var gmarkers = []; var htmls = []; //数组保存信息窗口的变体html获取方向形式openvar to_htmls = []; var from_htmls = []; // globalmapvariablevar map = null; var infowindow = new google.maps.InfoWindow({size:new google.maps.Size(150,50) });函数initialize(){var location = new google.maps.LatLng(50.871622,-4.131561); var mapOptions = {center:location,zoom:11,scrollwheel:false}; map = new google.maps.Map(document.getElementById(map),mapOptions); directionsDisplay.setMap(地图); directionsDisplay.setPanel(的document.getElementById( directionsPanel)); google.maps.event.addListener(map,'click',function(){infowindow.close();}); var image = {url:'http://maps.google.com/mapfiles/ms/micons/blue.png'}; var marker = new google.maps.Marker({position:location,map:map,animation:google.maps.Animation.DROP,icon:image,title:'Deer Park Dairy'}); var i = gmarkers.length; latlng =地点; //带有to here表单的信息窗口版本打开to_htmls [i] = html +'< br>路线:< b>到这里< \ / b> - < a href =javascript:fromhere('+ i +')> From here< \ / a>'+'< br>开始地址:< form action =javascript:getDirections() >'+'< input type =textSIZE = 40 MAXLENGTH = 40 name =saddrid =saddrvalue =/>< br>'+'< INPUT value =获取方向TYPE =buttononclick =getDirections()>< br>'+'步行< input type =checkboxname =walkid =walk/> &安培; NBSP;避免高速公路< input type =checkboxname =highwaysid =highways/>'+'< input type =hiddenid =daddrvalue ='+ latlng.lat()+ ','+ latlng.lng()+'/>'; //带有from here表单的信息窗口版本打开from_htmls [i] = html +'< br>路线:< a href =javascript:tohere('+ i +')> \ / A> - < b>从这里开始< \ / b>'+'< br>结束地址:< form action =javascript:getDirections()>'+'< input type =textSIZE = 40 MAXLENGTH = 40 name =daddrid =daddrvalue =/>< br>'+'< INPUT value =Get DirectionsTYPE =SUBMIT>< br>'+ 'Walk< input type =复选框name =walkid =walk/> &安培; NBSP;避免高速公路< input type =checkboxname =highwaysid =highways/>'+'< input type =hiddenid =saddrvalue ='+ latlng.lat()+ ','+ latlng.lng()+'/>'; //方向info的无效版本var html = marker.getTitle()+'< br>路线:< a href =javascript:tohere('+ i +')>到这里< \ /一个> - < a href =javascript:fromhere('+ i +')>从这里开始< \ / a>'; var contentString = html; google.maps.event.addListener(marker,'click',function(){map.setZoom(15); map.setCenter(marker.getPosition()); infowindow.setContent(contentString); infowindow.open(map,marker );}); //保存稍后需要用于side_bar的信息gmarkers.push(marker); htmls [i] = html;} google.maps.event.addDomListener(window,'load',initialize); // =====请求方向===== function getDirections(){// === =设置步行,避免高速公路选项==== var request = {}; if(document.getElementById(walk)。checked){request.travelMode = google.maps.DirectionsTravelMode.WALKING; } else {request.travelMode = google.maps.DirectionsTravelMode.DRIVING; } if(document.getElementById(highways)。checked){request.avoidHighways = true; } // ====设置开始和结束位置==== var saddr = document.getElementById(saddr)。value; var daddr = document.getElementById(daddr).value; request.origin = saddr; request.destination = daddr; directionsService.route(request,function(response,status){if(status == google.maps.DirectionsStatus.OK){directionsDisplay.setDirections(response);} else alert(Directions not found:+ status);}) ;} //此函数获取点击并打开相应的信息窗口函数myclick(i){google.maps.event.trigger(gmarkers [i],click);} //打开方向的函数forms functions tohere( i){// gmarkers [i] .openInfoWindowHtml(to_htmls [i]); infowindow.setContent(to_htmls [I]); infowindow.open(map,gmarkers [i]);} function fromhere(i){// gmarkers [i] .openInfoWindowHtml(from_htmls [i]); infowindow.setContent(from_htmls [I]); infowindow.open(map,gmarkers [i]);} //此Javascript基于//社区教会Javascript团队提供的代码// http://www.bisphamchurch.org.uk/ // http:// econym.org.uk/gmap///来自v2教程页面:// http://econym.org.uk/gmap/basic3.htm

  html,body,table {height:100%;宽度:100%; margin:0px; padding:0px} td,tr {height:100%; width:50%;}  

< script src = https://maps.googleapis.com/maps/api/js\"></script><table> < TR> < TD> < div id =mapstyle =width:100%; height:100%; border:2px solid#3872ac;>< / div> < / TD> < TD> < div id =directionsPanel>< / div> < / TD> < / table>


So I'm using the Google Maps API and currently I have a custom marker that highlights the location. What I would like to do, if possible, is be able to click it and have it bring up the google maps directions dialog (e.g THIS) that you get when clicking on a place name normally on google maps. At the minute I've just set it to zoom in on the marker, but obviously I'll just get rid of that function if I can get this to work.

Thanks in advance for any help.

Here is my code:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  function initialize() {

    var location = new google.maps.LatLng(50.871622, -4.131561);  

    var mapOptions = {
      center: location,
      zoom: 11,
      scrollwheel: false
    };

    var map = new google.maps.Map(document.getElementById("map"),
        mapOptions);

    var image = {
        url: 'img/mapmarker.png',
    };
    var marker = new google.maps.Marker({
        position: location,
        map: map,
        animation: google.maps.Animation.DROP,
        icon: image,
        title: 'Deer Park Dairy'
    });
    google.maps.event.addListener(marker, 'click', function() {
        map.setZoom(15);
        map.setCenter(marker.getPosition());
      });

  }

  google.maps.event.addDomListener(window, 'load', initialize);
</script>

解决方案

Your code with the directions handling from this example. The original functionality was written by Mike Williams for the Google Maps Javascript API v2 (which is now deprecated and turned off). So this Javascript is based on code provided by the Community Church Javascript Team (http://www.bisphamchurch.org.uk/, http://econym.org.uk/gmap/)

Working code snippet:

var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
// arrays to hold copies of the markers and html used by the side_bar 
// because the function closure trick doesnt work there 
var gmarkers = [];
var htmls = [];

// arrays to hold variants of the info window html with get direction forms open
var to_htmls = [];
var from_htmls = [];

// global "map" variable
var map = null;

var infowindow = new google.maps.InfoWindow({
  size: new google.maps.Size(150, 50)
});


function initialize() {

  var location = new google.maps.LatLng(50.871622, -4.131561);

  var mapOptions = {
    center: location,
    zoom: 11,
    scrollwheel: false
  };

  map = new google.maps.Map(document.getElementById("map"),
    mapOptions);

  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById("directionsPanel"));
  google.maps.event.addListener(map, 'click', function() {
    infowindow.close();
  });

  var image = {
    url: 'http://maps.google.com/mapfiles/ms/micons/blue.png'
  };
  var marker = new google.maps.Marker({
    position: location,
    map: map,
    animation: google.maps.Animation.DROP,
    icon: image,
    title: 'Deer Park Dairy'
  });

  var i = gmarkers.length;
  latlng = location;

  // The info window version with the "to here" form open
  to_htmls[i] = html + '<br>Directions: <b>To here<\/b> - <a href="javascript:fromhere(' + i + ')">From here<\/a>' +
    '<br>Start address:<form action="javascript:getDirections()">' +
    '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
    '<INPUT value="Get Directions" TYPE="button" onclick="getDirections()"><br>' +
    'Walk <input type="checkbox" name="walk" id="walk" /> &nbsp; Avoid Highways <input type="checkbox" name="highways" id="highways" />' +
    '<input type="hidden" id="daddr" value="' + latlng.lat() + ',' + latlng.lng() +
    '"/>';
  // The info window version with the "from here" form open
  from_htmls[i] = html + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here<\/a> - <b>From here<\/b>' +
    '<br>End address:<form action="javascript:getDirections()">' +
    '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
    '<INPUT value="Get Directions" TYPE="SUBMIT"><br>' +
    'Walk <input type="checkbox" name="walk" id="walk" /> &nbsp; Avoid Highways <input type="checkbox" name="highways" id="highways" />' +
    '<input type="hidden" id="saddr" value="' + latlng.lat() + ',' + latlng.lng() +
    '"/>';
  // The inactive version of the direction info
  var html = marker.getTitle() + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here<\/a> - <a href="javascript:fromhere(' + i + ')">From here<\/a>';
  var contentString = html;

  google.maps.event.addListener(marker, 'click', function() {
    map.setZoom(15);
    map.setCenter(marker.getPosition());
    infowindow.setContent(contentString);
    infowindow.open(map, marker);
  });
  // save the info we need to use later for the side_bar
  gmarkers.push(marker);
  htmls[i] = html;
}

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

// ===== request the directions =====
function getDirections() {
  // ==== Set up the walk and avoid highways options ====
  var request = {};
  if (document.getElementById("walk").checked) {
    request.travelMode = google.maps.DirectionsTravelMode.WALKING;
  } else {
    request.travelMode = google.maps.DirectionsTravelMode.DRIVING;
  }

  if (document.getElementById("highways").checked) {
    request.avoidHighways = true;
  }
  // ==== set the start and end locations ====
  var saddr = document.getElementById("saddr").value;
  var daddr = document.getElementById("daddr").value;

  request.origin = saddr;
  request.destination = daddr;
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    } else alert("Directions not found:" + status);
  });
}


// This function picks up the click and opens the corresponding info window
function myclick(i) {
  google.maps.event.trigger(gmarkers[i], "click");
}


// functions that open the directions forms
function tohere(i) {
  // gmarkers[i].openInfoWindowHtml(to_htmls[i]);
  infowindow.setContent(to_htmls[i]);
  infowindow.open(map, gmarkers[i]);
}

function fromhere(i) {
  // gmarkers[i].openInfoWindowHtml(from_htmls[i]);
  infowindow.setContent(from_htmls[i]);
  infowindow.open(map, gmarkers[i]);
}

// This Javascript is based on code provided by the
// Community Church Javascript Team
// http://www.bisphamchurch.org.uk/   
// http://econym.org.uk/gmap/
// from the v2 tutorial page at:
// http://econym.org.uk/gmap/basic3.htm

html,
body,
table {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
td,
tr {
  height: 100%;
  width: 50%;
}

<script src="https://maps.googleapis.com/maps/api/js"></script>
<table>
  <tr>
    <td>
      <div id="map" style="width:100%; height:100%; border: 2px solid #3872ac;"></div>
    </td>
    <td>
      <div id="directionsPanel"></div>
    </td>
  </tr>
</table>

这篇关于使用Google Maps API指示标记的方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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