Google maps API - Center map on client's current location

冷暖自知 提交于 2019-11-28 21:05:51
Praveen

Try using the below code to get the user's current location (GEOLOCATION):

 if (navigator.geolocation) {
     navigator.geolocation.getCurrentPosition(function (position) {
         initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
         map.setCenter(initialLocation);
     });
 }

For showing an example, I've removed your php code. Check this JSFiddle

Hope you understand.

To provide a useful map whether user allowed or denied the browser's "Allow location detection?" prompt (modify the default location to suit):

<script>
  function initMap() {

  gMap = new google.maps.Map(document.getElementById('map'));

  navigator.geolocation.getCurrentPosition(function(position) {
    // Center on user's current location if geolocation prompt allowed
    var initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    gMap.setCenter(initialLocation);
    gMap.setZoom(13);
  }, function(positionError) {
    // User denied geolocation prompt - default to Chicago
    gMap.setCenter(new google.maps.LatLng(39.8097343, -98.5556199));
    gMap.setZoom(5);
  });
}
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!