2

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

<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 中删除了 {timeout: 10000},它现在正在发出警报。脚本更新。

4

1 回答 1

3

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

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

于 2012-08-17T19:52:39.520 回答