首页 > 解决方案 > Google 协作平台 + 地图 Javascript API + HTML5 地理位置

问题描述

我正在尝试使用在 Google 站点内具有航路点和动态原点的路线来实现地图。我想根据访问 Google 站点的用户位置设置原点,并且我正在使用 HTML5 Geolocation API 来检索用户的地理位置。但是,我无法正确检索用户的地理位置。

在这里,您将找到我目前正在实施的代码。

<!DOCTYPE html>
<html>
  <head>
    <title>PATH A</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <style type="text/css">
      #map {
        height: 100%;
      }

      /* Optional: Makes the sample page fill the window. */
      html,
      body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
    <script>    
    function initMap() {
        const directionsService = new google.maps.DirectionsService();
        const directionsRenderer = new google.maps.DirectionsRenderer();
        const map = new google.maps.Map(document.getElementById("map"), {
          zoom: 8,
          center: { lat: 37.132, lng: 13.869 },
        });
        directionsRenderer.setMap(map);
        
        const onChangeHandler = function () {
          calculateAndDisplayRoute(directionsService, directionsRenderer);
        };
        
        window.onload = onChangeHandler;
    }
    
    function setPosition(position){
        currentOrigin = {};
        currentOrigin.lat = position.coords.latitude;
        currentOrigin.lng = position.coord.longitude;
    }
    
    function calculateAndDisplayRoute(directionsService, directionsRenderer){
    let currentOrigin = new google.maps.LatLng(37.081, 14.214);
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(setPosition);
        } else {
          // Browser doesn't support Geolocation
              console.log("Browser does not support geolocation");
        }
        const waypts = [];
        waypts.push({
            location: { lat: 37.261, lng: 13.588},
            stopover: true
        });
        directionsService.route({
            origin: currentOrigin,
            destination: {
             lat: 37.314 , lng: 13.576
            },
            optimizeWaypoints: false,
            waypoints: waypts,
            travelMode: google.maps.TravelMode.DRIVING
        }, (response, status) => {
            if(status === "OK" && response) {
                directionsRenderer.setDirections(response);
            } else {
                console.log("An error occurred: " + status);
            }
        });
    }
    </script>
  </head>
  <body>
    <div id="map"></div>

    <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=*********&callback=initMap&libraries=&v=weekly"
      async
    ></script>
  </body>
</html>

Google 协作平台的政策是否以某种方式阻止了 Geolocation API?如果是这样,还有其他方法可以设置动态原点吗?理想的解决方案是在站点上有一张地图,其中包含带有特定航路点的路线。

提前感谢您的关注。

标签: google-maps-api-3

解决方案


所以首先我认为你的 setPosition 回调函数中有一个错字,经度应该是position.coords.longitude。当导航器返回 lat 和 lng 时,您还需要设置谷歌地图对象的中心。现在 currentOrigin 超出了地图的范围,并且永远无法更新。您可以尝试的一件事是将地图对象的引用传递给 calculateAndDisplayRoute 并在 setPosition 回调中设置地图的位置。尝试这个:

function initMap() {
    const directionsService = new google.maps.DirectionsService();
    const directionsRenderer = new google.maps.DirectionsRenderer();
    const map = new google.maps.Map(document.getElementById("map"), {
      zoom: 8,
      center: { lat: 37.132, lng: 13.869 },
    });
    directionsRenderer.setMap(map);
    
    const onChangeHandler = function () {
      calculateAndDisplayRoute(directionsService, directionsRenderer, map);
    };
    
    window.onload = onChangeHandler;
}

function setPosition(position, map){
    currentOrigin = {};
    map.setCenter({ lat : position.coords.latitude, lng: position.coords.longitude });
}

function calculateAndDisplayRoute(directionsService, directionsRenderer, map){
let currentOrigin = new google.maps.LatLng(37.081, 14.214);
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function (position) {
         setPosition(position, map);
     });
    } else {
      // Browser doesn't support Geolocation
          console.log("Browser does not support geolocation");
    }
    const waypts = [];
    waypts.push({
        location: { lat: 37.261, lng: 13.588},
        stopover: true
    });
    directionsService.route({
        origin: currentOrigin,
        destination: {
         lat: 37.314 , lng: 13.576
        },
        optimizeWaypoints: false,
        waypoints: waypts,
        travelMode: google.maps.TravelMode.DRIVING
    }, (response, status) => {
        if(status === "OK" && response) {
            directionsRenderer.setDirections(response);
        } else {
            console.log("An error occurred: " + status);
        }
    });
}

我将地图对象传递给回调,以便可以在导航器位置调用 setCenter。


推荐阅读