使用Geolocation以引导模式加载地图,标记不会居中

Using Geolocation to load a map in a bootstrap modal, the marker is not centered

本文关键字:地图 Geolocation 加载 模式 使用      更新时间:2023-09-26

我正试图在基于地理位置的引导模式中加载的地图中居中放置一个标记,以获取用户的当前位置。剩下的已经在小提琴里解释了
JS小提琴

HTML:

<a href="#locate" data-toggle="modal">Open Modal</a>
<div id="locate" class="modal fade" role="dialog">
  <div class="modal-dialog modal-lg">                               
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title-contact">My Location</h4>
      </div>
      <div class="modal-body">              
        <div id="map"></div>
      </div>
    </div>                          
  </div>
</div>

JavaScript:

function initMap(){
  var loc = {lat:0,lng:0};
  if (navigator.geolocation){
  navigator.geolocation.getCurrentPosition(showPosition);
  }
  else {
  alert("Geolocation is not supported by this browser.");
  }
function showPosition(position){ 
  loc.lat=position.coords.latitude;
  loc.lng=position.coords.longitude;
  var geocoder = new google.maps.Geocoder();
  var latLng = new google.maps.LatLng(loc.lat, loc.lng);
  console.log(latLng);
  if (geocoder) {
    geocoder.geocode({ 'latLng': latLng}, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
    var markerOptions = new google.maps.Marker({
    clickable: true,
    flat: true,
    map: map,
    position: results[0].geometry.location,
    title: "You are here",
    visible:true,
    icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
    });
    var marker = new google.maps.Marker(markerOptions);
    map.setCenter(results[0].geometry.location);
    }
    else {
      console.log("Geocoding failed: " + status);
      }
    });
  } 
  }
  var latLong = new google.maps.LatLng(loc.lat, loc.lng);
  var mapOptions = {
    center: latLong,
    useCurrentLocation : true,
    zoom: 8,
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var bounds = new google.maps.LatLngBounds();
bounds.extend(latLong);
map.fitBounds(bounds);
    var listener = google.maps.event.addListener(map, "idle", function() { 
    if (map.getZoom() > 16) map.setZoom(16); 
  google.maps.event.removeListener(listener); 
    });
$('#locate').on('shown', function () {
      google.maps.event.trigger(map, "resize");
});
}

任何帮助都将不胜感激。

在触发调整大小事件之前存储地图的中心,并在触发调整尺寸事件之后重新分配中心:

$('#locate').on('shown.bs.modal', function () {
   var center=map.getCenter();
   google.maps.event.trigger(map, "resize");
   map.setCenter(center);
});

https://jsfiddle.net/doktormolle/9tr8dmax/