Search code examples
google-maps-api-3geolocation

Google map API geolocation after first display of the map


This code takes a big list of (400) markers and adds it to the map, at the end, it shows the whole map including all the markers.

What I have tried to achieve is: when geolocation is available, center the map on location, zoom to level 16 and refresh the map to show it, otherwise, let the whole big map show... I have read and tried many different things, but the geolocation must happen before the map is created. I want to make it happen after. I show you my code here and the temporary link to the working site: http://studioteknik.co/brasseursillimites.com/detaillants/

function initialize()
{
    var map = new google.maps.Map(document.getElementById('map-canvas'));
    var bounds = new google.maps.LatLngBounds();
    var infowindow = new google.maps.InfoWindow();

    for (var i in locations) {

        var p = locations[i];
        var latlng = new google.maps.LatLng(p[1], p[2]);
        bounds.extend(latlng);

        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title: p[0]
        });

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(this.title);
            infowindow.open(map, this);
        });
    }

    map.fitBounds(bounds);
}

google.maps.event.addDomListener(window, 'load', initialize);

Solution

  • Here is a simple example of geolocation. Just add the geolocation code anywhere after the map object is created. If the user doesn't allow geolocation, the map will be shown at the default location / zoom level.

    function initialize() {
    
        var mapOptions = {
            zoom: 10,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: new google.maps.LatLng(0,0)
        };
    
        var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    
        // Geolocation code
        if (navigator.geolocation) {
    
            navigator.geolocation.getCurrentPosition(function (position) {
    
                map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
                map.setZoom(16);
            });
        }
    }
    
    initialize();
    

    JSFiddle demo