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

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


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>