1

我有以下代码来检测访问者的 GPS 位置并将其显示在 Google Maps JavaScript v3 地图上。一切都按我的意愿工作,但代码不会按我的意愿居中或缩放 - 它简单地使用标准位置(就在亚洲)!我希望它适合地图上的标记。

var rendererOptions = {
    draggable: false
};

if(navigator.geolocation) {
    var timeoutVal = 10 * 1000 * 1000;

    navigator.geolocation.watchPosition(
        displayPosition,
        displayError,
        { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
    );
} else {
    alert('Din webbläsare stödjer inte någon geologisk lokalisering med hjälp av HTML5');
}

var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var marker_gps;
var map_gps;
var options_gps;





function displayPosition(position) {


    /***********************
    **    GPS-POSITION    **
    ************************/

    directionsDisplay = new google.maps.DirectionsRenderer();
    localStorage.coor = position.coords.latitude.toFixed(6) + ',' + position.coords.longitude.toFixed(6);

    var gps_coor = new google.maps.LatLng(position.coords.latitude.toFixed(6), position.coords.longitude.toFixed(6));

    if(typeof(marker) != 'undefined') marker.setMap(null);

    localStorage.accuracy = position.coords.accuracy;
    document.getElementById('accuracy').innerHTML = number_format(localStorage.accuracy) + ' meter';

    directionsDisplay.setMap(map_gps);
    directionsDisplay.setPanel(document.getElementById('directions-panel'));

    marker_gps = new google.maps.Marker({
        position: gps_coor,
        draggable: false,
        map: map_gps
    });

    var circle_gps = new google.maps.Circle({
        center: gps_coor,
        radius: position.coords.accuracy,
        map: map_gps,
        fillColor: '#3333ff',
        fillOpacity: 0.2,
        strokeColor: '#3333ff',
        strokeOpacity: 0.5,
        strokeWeight: 1
    });



    /*****************************
    **    FÄRDSÄTT (DISTANS)    **
    ******************************/

    var start = new google.maps.LatLng(position.coords.latitude.toFixed(6), position.coords.longitude.toFixed(6));
    var stop = new google.maps.LatLng(<?php echo $photo['coordinates_latitude'].','.$photo['coordinates_longitude']; ?>);

    var request = {
        origin: start,
        destination: stop,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if(status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });

    directionsService.route(request, function(response, status) {
        if(status == google.maps.DirectionsStatus.OK) {
            var distance = (response.routes[0].legs[0].distance.value / 1000).toFixed(0);
            var duration = secondsToString(response.routes[0].legs[0].duration.value);

            document.getElementById('distance').innerHTML = 'Cirka ' + distance + ' kilometer';
            document.getElementById('duration').innerHTML = 'Cirka ' + duration;

            directionsDisplay.setDirections(response);
        }
    });


}



function initialize_gps() {
    var coor = new google.maps.LatLng(localStorage.coor);
    var bounds = new google.maps.LatLngBounds();

    options_gps = {
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: google.maps.LatLng(localStorage.coor),
        streetViewControl: false
    }

    map_gps = new google.maps.Map(document.getElementById('map-distance'), options_gps);
    map_gps.fitBounds(bounds);
}







function secondsToString(seconds) {
    var numdays = Math.floor(seconds / 86400);
    var numhours = Math.floor((seconds % 86400) / 3600);
    var numminutes = Math.floor(((seconds % 86400) % 3600) / 60);

    return (numdays != 0 ? (numdays == 1 ? '1 dag' : numdays + ' dagar') + ', ' : '')
         + (numhours != 0 ? (numhours == 1 ? '1 timme' : numhours + ' timmar') + (numdays != 0 ? ', ' : ' och ') : '')
         + (numminutes != 0 ? (numminutes == 1 ? '1 minut' : numminutes + ' minuter') : '');
}

function displayError(error) {
    var errors = {
        1: 'Permission denied',
        2: 'Position unavailable',
        3: 'Request timeout'
    };

    alert('Error: ' + errors[error.code]);
}

我怎样才能使它工作?

提前致谢。

编辑

initialize_gps这是函数的编辑部分。这部分不起作用 - 没有发生任何新情况。它只是像以前一样将地图集中在亚洲。

function initialize_gps() {
    var coor = new google.maps.LatLng(localStorage.coor);
    var bounds = new google.maps.LatLngBounds();

    options_gps = {
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: google.maps.LatLng(localStorage.coor),
        streetViewControl: false
    }

    map_gps = new google.maps.Map(document.getElementById('map-distance'), options_gps);
    map_gps.fitBounds(bounds);
}

编辑

我已将整个代码复制粘贴到 jsFiddle。链接:http: //jsfiddle.net/edgren/WRxt4/

4

1 回答 1

4

将地图显示拟合到一组标记的一般解决方案是将它们添加到空的google.maps.LatLngBounds 对象(通过调用 bounds.extend),然后使用该边界调用map.fitBounds

function setMarkers(map) {
  var bounds = new google.maps.LatLngBounds();
  // Adds markers to the map.
  for (let i = 0; i < beaches.length; i++) {
    const beach = beaches[i];
    var marker = new google.maps.Marker({
      position: { lat: beach[1], lng: beach[2] },
      map,
      title: beach[0],
    });
    bounds.extend(marker.getPosition());
  }
  map.fitBounds(bounds);
}

// The following example creates complex markers to indicate beaches near
// Sydney, NSW, Australia. Note that the anchor is set to (0,32) to correspond
// to the base of the flagpole.
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 10,
    center: { lat: 0, lng: 0 },
  });
  setMarkers(map);
}
// Data for the markers consisting of a name, a LatLng and a zIndex for the
// order in which these markers should display on top of each other.
const beaches = [
  ["Bondi Beach", -33.890542, 151.274856, 4],
  ["Coogee Beach", -33.923036, 151.259052, 5],
  ["Cronulla Beach", -34.028249, 151.157507, 3],
  ["Manly Beach", -33.80010128657071, 151.28747820854187, 2],
  ["Maroubra Beach", -33.950198, 151.259302, 1],
];

function setMarkers(map) {
  var bounds = new google.maps.LatLngBounds();
  // Adds markers to the map.
  for (let i = 0; i < beaches.length; i++) {
    const beach = beaches[i];
    var marker = new google.maps.Marker({
      position: { lat: beach[1], lng: beach[2] },
      map,
      title: beach[0],
    });
    bounds.extend(marker.getPosition());
  }
  map.fitBounds(bounds);
}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Complex Marker Icons</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <!-- jsFiddle will insert css and js -->
  </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=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly"
      async
    ></script>
  </body>
</html>

于 2012-10-21T22:27:44.217 回答