谷歌地图与目标文本框

时间:2012-03-20 03:38:20

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

我想将谷歌地图嵌入带有两个文本框的网站。我想在每个文本框中放置一个目的地,然后按一个“开始”按钮,该按钮跟踪两个文本框中输入的两个目的地的路线。

如果谷歌地图不是最简单的方法,那么我是否可以使用这个想法。

感谢

1 个答案:

答案 0 :(得分:2)

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
var map;
var directionsService = new google.maps.DirectionsService();

function initialize() {

    var rendererOptions = {
            draggable: true
        };

    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);

    var my_place = new google.maps.LatLng(17.435979,78.448196);
    var myOptions = {
        zoom:14,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: my_place
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
}

function calcRoute() {
  var start = document.getElementById("Start").value;
  var end = document.getElementById("Destination").value;
  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();
});
</script>

<div id='map_canvas' style='width: 500px; height: 400px'></div>
<form name="GoogleMapForm" method="post" action="">
Start: <input type="text" name="Start" id="Start" /><br />
Destination: <input type="text" name="Destination" id="Destination" /><br />
<input type="button" name="Go" value="Go" onclick="javascript: calcRoute()" />
</form>

以上代码有助于获得所需内容。表格有Start&amp;目标文本框,您必须手动输入地址。如果您想要自动填写这些文本框(例如,在您输入地址时引导您,请点击此链接“https://google-developers.appspot.com/maps/documentation/javascript/examples/places-autocomplete").