Search code examples
javascriptgoogle-mapsgeolocationgoogle-maps-advanced-marker-element

How to set the Advanced Marker on the device's location, on a Google Map?


I get it right to get the location of the device and center the map on it, I also succeed in creating a Marker but I don't get it right to combine the 2. I want to set the marker to the device's current location. Here's my code so far:

let map, infoWindow;


async function initMap() {
    const { Map } = await google.maps.importLibrary("maps");
    const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

    map = new google.maps.Map(document.getElementById("map"), {
        center: { lat: -33.9778791, lng: 22.4188544 },
        zoom: 15,
        disableDefaultUI: true
    });

    infoWindow = new google.maps.InfoWindow();

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            (position) => {
                const pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude,
                };

                map.setCenter(pos);

                const marker = new AdvancedMarkerElement({
                    map: map,
                    position: pos,
                });

                infoWindow.setPosition(pos);
                infoWindow.setContent("Location found.");
                infoWindow.open(map, marker);
            },
            () => {
                handleLocationError(true, infoWindow, map.getCenter());
            }
        );
    } else {
        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."
    );
    infoWindow.open(map);
}

window.initMap = initMap;

With this code nothing happens. The screen is empty. With the code in Add an advance marker the marker is shown at the hardcoded location. With the code in Geolocation the map loads with the device's location without a marker.

How is this done correctly?


Solution

  • I forgot to call initMap() and now that I'm calling it the marker loads successfully. Also, I added the mapId. Here's the corrected code:

    let map, infoWindow;
    
    
    async function initMap() {
        const { Map } = await google.maps.importLibrary("maps");
        const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
    
        map = new google.maps.Map(document.getElementById("map"), {
            center: { lat: -33.9778791, lng: 22.4188544 },
            zoom: 15,
            mapId: "DEMO_MAP_ID",
            disableDefaultUI: true
        });
    
        infoWindow = new google.maps.InfoWindow();
    
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    const pos = {
                        lat: position.coords.latitude,
                        lng: position.coords.longitude,
                    };
    
                    map.setCenter(pos);
    
                    const marker = new AdvancedMarkerElement({
                        map: map,
                        position: pos,
                        
                    });
    
                    infoWindow.setPosition(pos);
                    infoWindow.setContent("Location found.");
                    infoWindow.open(map, marker);
                },
                () => {
                    handleLocationError(true, infoWindow, map.getCenter());
                }
            );
        } else {
            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."
        );
        infoWindow.open(map);
    }
    
    window.initMap = initMap;
    initMap();