【问题标题】:Google Maps API to get directions using PHP and MySQL使用 PHP 和 MySQL 获取路线的 Google Maps API
【发布时间】:2017-07-20 18:24:18
【问题描述】:

我正在尝试让 Google 地图自动为存储在我的数据库中的目的地设置行车路线。基本上,我的数据库中有几个地址(即:制造商),我希望能够输入邮政编码(或地址)以接收从该邮政编码/地址到所有可用制造商的路线(也许是花哨的额外,获取最近的制造商)。我以前从未使用过 Google Maps API,所以我对此感到相当困惑。到目前为止,我只能为可用的制造商设置标记。至于行车路线,我找了好几个小时,消化起来有点复杂。到目前为止,您建议我对这段代码采取什么方式(没有双关语)?

echo "<script>
        var locations = 
        [
        ";
            for($i = 0; $i < sizeof($locations); $i++)
            {
                echo "['".$locations[$i][0]."', '".$locations[$i][1]."', ".$locations[$i][2].", ".$locations[$i][3].", ". ($i+1) ." ]";
                if (! ($i == (sizeof($locations)-1)) )
                    echo ",";
            }
        echo "];

        var map = new google.maps.Map(document.getElementById('map'), 
        {
            zoom: 15,
            center: new google.maps.LatLng(45.892235, -72.5371626),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        var infowindow = new google.maps.InfoWindow();

        var marker, i;

        for (i = 0; i < locations.length; i++) 
        {
            marker = new google.maps.Marker(
            {
                position: new google.maps.LatLng(locations[i][2], locations[i][3]),
                map: map
            });

            google.maps.event.addListener(marker, 'click', (function(marker, i) 
            {
                return function() {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
            }
          })(marker, i));
        }
</script>";

【问题讨论】:

  • 使用json_encode php函数编码位置数组php.net/manual/es/function.json-encode.php
  • @RolandoCorratgeNieves 我为什么要这么做?
  • 试试echo "location=".json_encode($x).";"; 看看你得到了什么也许你可以替换整个for循环

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


【解决方案1】:

在这里你有你的问题的第一个答案,希望这可以帮助。

jQuery(document).ready(function(){

  var locations = [
    ["a","Title A",46.3,-72.5],
    ["b","Title B",45.9,-72.4],
    ["c","Title C",45.6,-72.1]
  ] ;

  var map = new google.maps.Map(
    document.getElementById('map'), 
    {
      zoom: 7,
      center: new google.maps.LatLng(45.892235, -72.5371626),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
  );

  jQuery(locations).each(function(k,v) {
    
    locations[k].push('what s in index 4 ?') ; // Push in index 4
    
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(v[2],v[3]),
      map: map,
      title: v[1]
    })
    locations[k].push(marker) ;

  }) ;

  var directionsService = new google.maps.DirectionsService;
  var directionDisplays = [] ; // We need to store displays to be abled to remove them on each "getRoute" click.

  document.getElementById('getRoutes').addEventListener('click', getRoutes);

  function getRoutes() {

  	// Removing existing routes if any
    for ( i = 0 ; i < directionDisplays.length ; i++ )
      directionDisplays[i].setMap(null) ;

    directionDisplays = [] ;

    // Now the important part : for each location we look for the route
    jQuery(locations).each(function(k,v) {
    	
    	directionsService.route({
        	origin: document.getElementById('whereami').value,
          	destination: new google.maps.LatLng(v[2],v[3]) ,
          	travelMode: 'DRIVING'
        }, function (response, status) {
          if (status === 'OK') {
          	// This callback is call asynchronous, this is probably why it's complicated to access locations[k]
            var directionsDisplay = new google.maps.DirectionsRenderer ;
            directionsDisplay.setMap(map) ;
            // We remove the marker "B" added by directionsDisplay.
            directionsDisplay.setOptions( { suppressMarkers: true } );
            directionsDisplay.setDirections(response);
            directionDisplays.push(directionsDisplay) ;
            var point = response.routes[ 0 ].legs[ 0 ];

            // We affect the direction to the marker to make it accessible later
            locations[k][5].duration = point.distance.text ;

            // And know we just have to add a listener.
		    locations[k][5].addListener('click',function(){
		      	console.log(this.title,this.duration) ;
		    }) ;

          } else {
            window.alert('Directions request failed due to ' + status);
          }
       }
      );
    }) ;
  }

}) ;
div#map {
width:50% ;
height:250px ;
float:left ;
}

div#boutons {
float:right;
width:200px ;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
<div id="boutons">
  <input type="text" id="whereami" value="Ottawa" />
  <button id="getRoutes">get routes</button>
</div>

【讨论】:

  • 谢谢,它就像一个魅力。但是,我认为 API 可以让你自动点击一条路线来选择它(就像在谷歌地图上一样)。有没有办法这样做,还是我必须使用折线自己绘制路线?
  • 我不认为你可以在方向显示上添加点击监听器,也许你应该看看响应对象,它可能包含完整的路径,所以你可以自己绘制而不是使用 @ 987654325@.
  • 太好了,我没有点击路线,而是为每个标记添加了一个事件侦听器,以便显示行程距离和行程时间。但是,它仅适用于循环中的最后一个位置。就好像来自 API 的响应很慢,它只获取最后一个结果(并且由于某种原因输出结果的时间与循环值相同)
  • 你应该考虑添加你的实际代码,这样我们就可以看到你在哪里
  • pastebin.com/4QQhuXFT 见“警报(姓名);”这就是它输出最后一个位置名称 4 次的地方(我在数据库中有 4 个位置),而它应该输出每个位置名称。
猜你喜欢
  • 2013-01-07
  • 2013-02-25
  • 1970-01-01
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 2013-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多