Google将我的位置和方式映射到我的工作街

时间:2016-09-06 10:46:38

标签: javascript google-maps

我有代码:



<script type="text/javascript">
    var my={directionsSVC:new google.maps.DirectionsService(),maps:{},routes:{}};
    /**
        * base-class
        * @param points optional array array of lat+lng-values defining a route
        * @return object Route
    **/
    function Route(points) {
        this.origin       = null;
        this.destination  = null;
        this.waypoints    = [];
        if(points && points.length>1) { this.setPoints(points);}
        return this;
    };

    /**
        *  draws route on a map
        *
        * @param map object google.maps.Map
        * @return object Route
    **/
    Route.prototype.drawRoute = function(map) {
        var _this=this;
        my.directionsSVC.route(
          {"origin": this.origin,
           "destination": this.destination,
           "waypoints": this.waypoints,
           "travelMode": google.maps.DirectionsTravelMode.DRIVING
          },
          function(res,sts) {
                if(sts==google.maps.DirectionsStatus.OK){
                    if(!_this.directionsRenderer) { _this.directionsRenderer=new google.maps.DirectionsRenderer({ "draggable":true }); }
                    _this.directionsRenderer.setMap(map);
                    _this.directionsRenderer.setDirections(res);
                    google.maps.event.addListener(_this.directionsRenderer,"directions_changed", function() { _this.setPoints(); } );
                }
          });
        return _this;
    };

    /**
    * sets map for directionsRenderer
    * @param map object google.maps.Map
    **/
    Route.prototype.setGMap = function(map){ this.directionsRenderer.setMap(map); };

    /**
    * sets origin, destination and waypoints for a route
    * from a directionsResult or the points-param when passed
    *
    * @param points optional array array of lat+lng-values defining a route
    * @return object Route
    **/
    Route.prototype.setPoints = function(points) {
        this.origin = null;
        this.destination = null;
        this.waypoints = [];
        if(points) {
          for(var p=0;p<points.length;++p){
            this.waypoints.push({location:new google.maps.LatLng(points[p][0], points[p][1]),stopover:false});
          }
          this.origin=this.waypoints.shift().location;
          this.destination=this.waypoints.pop().location;
        }
        else {
          var route=this.directionsRenderer.getDirections().routes[0];
          for(var l=0;l<route.legs.length;++l) {
            if(!this.origin)this.origin=route.legs[l].start_location;
            this.destination = route.legs[l].end_location;

            for(var w=0;w<route.legs[l].via_waypoints.length;++w) { this.waypoints.push({location:route.legs[l].via_waypoints[w], stopover:false});}
          }
          //the route has been modified by the user when you are here you may call now this.getPoints() and work with the result
        }
        return this;
    };

    /**
    * retrieves points for a route
    *
    * @return array
    **/
    Route.prototype.getPoints = function() {
      var points=[[this.origin.lat(),this.origin.lng()]];

      for(var w=0;w<this.waypoints.length;++w) { points.push([this.waypoints[w].location.lat(), this.waypoints[w].location.lng()]);}
      points.push([this.destination.lat(), this.destination.lng()]);
      return points;
    };

    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
      } else {
        alert("Geolocation is not supported by this browser.");
      }
    }
    function showPosition(position) {
      var lat = position.coords.latitude;
      var lng = position.coords.longitude;
      map.setCenter(new google.maps.LatLng(lat, lng));
    }

    function initialize() {
      var myOptions = { zoom: 8, center: new google.maps.LatLng(-34.397, 150.644), mapTypeId: google.maps.MapTypeId.ROADMAP };
        my.maps.map1 = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        my.routes.r0 = new Route([[55.930385, -3.118425],[50.909700, -1.40435]]).drawRoute(my.maps.map1);

        my.routes.rx=new Route();
    }
    google.maps.event.addDomListener(window, "load", initialize);
</script>

<div id="map_canvas" style="height:300px;width:300px;"></div>
&#13;
&#13;
&#13;

我希望从我的观点到我的工作铺平道路,我该怎么做?我有getLocation()和showPosition(),我不知道如何在我的代码上应用这些函数。请帮忙决定。

1 个答案:

答案 0 :(得分:0)

所以,问题是javascript的异步性。执行功能需要一些时间。

javascript解决方案是回调。你告诉一个功能:当你完成时;执行此功能;您将该函数提供给参数。

  • google.maps.event.addDomListener(窗口,&#34;加载&#34;,初始化)表示:加载窗口(页面)时,执行初始化功能。

  • navigator.geolocation.getCurrentPosition(showPosition);表示:当您(javascript)找到用户位置时,执行showPosition。

对于谷歌地图,我会建议:首先显示默认地图中心,默认缩放;然后,如果找到用户位置,则平移(并可能缩放)到该位置 所以这样的事情(注意:代码看起来像是先执行底部,最后一部分是最后一部分;这是因为你首先想要在使用之前对函数进行decrare):

<script>
...

function showPosition(position) {
  var lat = position.coords.latitude;
  var lng = position.coords.longitude;      
  map.setCenter(new google.maps.LatLng(lat, lng));
}

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } 
  else {
    //alert("Geolocation is not supported by this browser.");
  }
}

function initialize() {
  // make the map
  var myOptions = { zoom: 8, center: new google.maps.LatLng(-34.397, 150.644), ...}
  ...
  // now ask for the user location
  getLocation();
}

// page is loaded
google.maps.event.addDomListener(window, "load", initialize);
</script>

我同意el solo lobo。最好从一个简单的例子构建一个地图,然后添加组件和功能;而不是逆向工程复杂的代码。他们做某些事情的原因可能与你需要的代码无关。