谷歌地图/GMAP3 - 绘制从用户地理位置到已知目的地的路线 - 需要帮助

google maps/gmap3 - plotting a route to a known destination from a user's geolocation - help needed

本文关键字:目的地 帮助 绘制 GMAP3 用户 谷歌地图 地理位置      更新时间:2023-09-26

我正在尝试编写一个脚本来获取用户的地理位置 - 如果他们启用了它,并绘制到预定义目的地的路线。 如果他们没有启用地理位置,它应该只绘制预定义的位置。 脚本不起作用,但您应该能够通过查看代码来很好地了解我正在尝试做什么。 我走在正确的轨道上吗? 谁能发现为什么它不是加工?

<script type="text/javascript">
       $(function (){
        var dest = "Unit 20, Tallaght Business Centre, Whitestown Road, Tallaght Business Park, Ireland";
        if(geolocEnabled()){
            getLocation();
        }else{
            plotMarker(dest);
        }
        //check if geolocation enabled
        function geolocEnabled(){
            return navigator.geolocation;
        }
        //plot marker for VRF office
        function plotMarker(dest){
            $('#map').gmap3(
              { action: 'addMarker',
                address: dest,
                map:{
                  center: true,
                  zoom: 14
                },
                marker:{
                  options:{
                    draggable: false
                  }
                }
              }
            );
        }
        //get user's location
        function getLocation(){
            $('#map').gmap3(
            { action : 'geoLatLng',
              callback : function(latLng){
                if (latLng){
                  plotRoute(latLng, dest);  
                  return;
                } else {
                  alert("Unable to determine your location. Enable geolocation services and try again, or consult the map for our location.");
                  plotMarker(dest);
                }
              }
            });
          }
        //plot route
        function plotRoute(latLng, dest){
        $('#map').gmap3(
          { action:'getRoute',
            options:{
              origin: latLng,
              destination: dest,
              travelMode: google.maps.DirectionsTravelMode.DRIVING
            },
            callback: function(results){
              if (!results) return;
              $(this).gmap3(
                { action:'init', 
                  zoom: 7, 
                  mapTypeId: google.maps.MapTypeId.ROADMAP, 
                  streetViewControl: true,
                  center: [53.337433,-6.2661]
                },
                { action:'addDirectionsRenderer',
                  panelID: 'directions-panel',
                  options:{
                    preserveViewport: true,
                    draggable: false,
                    directions:results
                  }
                }
              );
            }
          }
        );
      }
    });
    </script>

所有的帮助非常感谢。

编辑:当我运行脚本时,我什至没有在浏览器中收到地理位置警告。

编辑:我从getLocation中删除了{超时:10000},现在它正在进入警报。 脚本已更新。

地理定位是一个异步过程,当getLocation()完成后,结果将不可用。

$.gmap3.geoLatLng的回调中调用plotRoute()并提供预期的参数(latLng,dest)