Search code examples
apigoogle-mapsgeolocationregistration

How can I show automatically registered users geolocation in a global map with google maps api as they register?


I'm trying to show all users geolocation from a web site in a map. Through google maps API documentation I've got a way to show my location as user. But, how I make it for show all geolocation from the registered people on the website?

<div id="map"></div>
<script>

  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -34.397, lng: 150.644},
      zoom: 6
    });
    var infoWindow = new google.maps.InfoWindow({map: map});

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

        infoWindow.setPosition(pos);
        infoWindow.setContent('Location found.');
        map.setCenter(pos);
      }, function() {
        handleLocationError(true, infoWindow, map.getCenter());
      });
    } else {
      // Browser doesn't support Geolocation
      handleLocationError(false, infoWindow, map.getCenter());
    }
  }

  function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
                          'Error: The Geolocation service failed.' :
                          'Error: Your browser doesn\'t support geolocation.');
  }
</script>

Solution

  • Create objects of the google.maps.Marker() type, set a position using the setPosition function of it and add it to your map using the setMap function.

    Example (Lat/Lng is the center of Germany - insert your users coordinates there):

    var marker=new google.maps.Marker();  
    // use your registered user coordinates here
    marker.setPosition(new google.maps.LatLng(48.14544, 8.19208)); 
    marker.setMap(map);
    

    Additionally you can use boundaries to make your map autozoom to get every marker visible:

    var bounds=new google.maps.LatLngBounds();
    ...
    bounds.extend(marker.getPosition());
    ...
    map.fitBounds(bounds);