将地图居中并缩放以适合屏幕上的标记

Eri*_*rik 2 google-maps-api-3 fitbounds

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

\n\n
var rendererOptions = {\n    draggable: false\n};\n\nif(navigator.geolocation) {\n    var timeoutVal = 10 * 1000 * 1000;\n\n    navigator.geolocation.watchPosition(\n        displayPosition,\n        displayError,\n        { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }\n    );\n} else {\n    alert(\'Din webbl\xc3\xa4sare st\xc3\xb6djer inte n\xc3\xa5gon geologisk lokalisering med hj\xc3\xa4lp av HTML5\');\n}\n\nvar directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);\nvar directionsService = new google.maps.DirectionsService();\nvar marker_gps;\nvar map_gps;\nvar options_gps;\n\n\n\n\n\nfunction displayPosition(position) {\n\n\n    /***********************\n    **    GPS-POSITION    **\n    ************************/\n\n    directionsDisplay = new google.maps.DirectionsRenderer();\n    localStorage.coor = position.coords.latitude.toFixed(6) + \',\' + position.coords.longitude.toFixed(6);\n\n    var gps_coor = new google.maps.LatLng(position.coords.latitude.toFixed(6), position.coords.longitude.toFixed(6));\n\n    if(typeof(marker) != \'undefined\') marker.setMap(null);\n\n    localStorage.accuracy = position.coords.accuracy;\n    document.getElementById(\'accuracy\').innerHTML = number_format(localStorage.accuracy) + \' meter\';\n\n    directionsDisplay.setMap(map_gps);\n    directionsDisplay.setPanel(document.getElementById(\'directions-panel\'));\n\n    marker_gps = new google.maps.Marker({\n        position: gps_coor,\n        draggable: false,\n        map: map_gps\n    });\n\n    var circle_gps = new google.maps.Circle({\n        center: gps_coor,\n        radius: position.coords.accuracy,\n        map: map_gps,\n        fillColor: \'#3333ff\',\n        fillOpacity: 0.2,\n        strokeColor: \'#3333ff\',\n        strokeOpacity: 0.5,\n        strokeWeight: 1\n    });\n\n\n\n    /*****************************\n    **    F\xc3\x84RDS\xc3\x84TT (DISTANS)    **\n    ******************************/\n\n    var start = new google.maps.LatLng(position.coords.latitude.toFixed(6), position.coords.longitude.toFixed(6));\n    var stop = new google.maps.LatLng(<?php echo $photo[\'coordinates_latitude\'].\',\'.$photo[\'coordinates_longitude\']; ?>);\n\n    var request = {\n        origin: start,\n        destination: stop,\n        travelMode: google.maps.DirectionsTravelMode.DRIVING\n    };\n\n    directionsService.route(request, function(response, status) {\n        if(status == google.maps.DirectionsStatus.OK) {\n            directionsDisplay.setDirections(response);\n        }\n    });\n\n    directionsService.route(request, function(response, status) {\n        if(status == google.maps.DirectionsStatus.OK) {\n            var distance = (response.routes[0].legs[0].distance.value / 1000).toFixed(0);\n            var duration = secondsToString(response.routes[0].legs[0].duration.value);\n\n            document.getElementById(\'distance\').innerHTML = \'Cirka \' + distance + \' kilometer\';\n            document.getElementById(\'duration\').innerHTML = \'Cirka \' + duration;\n\n            directionsDisplay.setDirections(response);\n        }\n    });\n\n\n}\n\n\n\nfunction initialize_gps() {\n    var coor = new google.maps.LatLng(localStorage.coor);\n    var bounds = new google.maps.LatLngBounds();\n\n    options_gps = {\n        zoom: 8,\n        mapTypeId: google.maps.MapTypeId.ROADMAP,\n        center: google.maps.LatLng(localStorage.coor),\n        streetViewControl: false\n    }\n\n    map_gps = new google.maps.Map(document.getElementById(\'map-distance\'), options_gps);\n    map_gps.fitBounds(bounds);\n}\n\n\n\n\n\n\n\nfunction secondsToString(seconds) {\n    var numdays = Math.floor(seconds / 86400);\n    var numhours = Math.floor((seconds % 86400) / 3600);\n    var numminutes = Math.floor(((seconds % 86400) % 3600) / 60);\n\n    return (numdays != 0 ? (numdays == 1 ? \'1 dag\' : numdays + \' dagar\') + \', \' : \'\')\n         + (numhours != 0 ? (numhours == 1 ? \'1 timme\' : numhours + \' timmar\') + (numdays != 0 ? \', \' : \' och \') : \'\')\n         + (numminutes != 0 ? (numminutes == 1 ? \'1 minut\' : numminutes + \' minuter\') : \'\');\n}\n\nfunction displayError(error) {\n    var errors = {\n        1: \'Permission denied\',\n        2: \'Position unavailable\',\n        3: \'Request timeout\'\n    };\n\n    alert(\'Error: \' + errors[error.code]);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我怎样才能让它发挥作用?

\n\n

提前致谢。

\n\n

编辑

\n\n

这是编辑后的部分initialize_gps函数的编辑部分。这部分不起作用——没有发生任何新的事情。它像以前一样将地图置于亚洲中心。

\n\n
function initialize_gps() {\n    var coor = new google.maps.LatLng(localStorage.coor);\n    var bounds = new google.maps.LatLngBounds();\n\n    options_gps = {\n        zoom: 8,\n        mapTypeId: google.maps.MapTypeId.ROADMAP,\n        center: google.maps.LatLng(localStorage.coor),\n        streetViewControl: false\n    }\n\n    map_gps = new google.maps.Map(document.getElementById(\'map-distance\'), options_gps);\n    map_gps.fitBounds(bounds);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

编辑

\n\n

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

\n

geo*_*zip 6

将地图显示适合一组标记的一般解决方案是将它们添加到空的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);
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)
// 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);
}
Run Code Online (Sandbox Code Playgroud)
/* 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;
}
Run Code Online (Sandbox Code Playgroud)