Gianlo478
Gianlo478

Reputation: 31

Google Geolocation API - red destination marker

I am learning how to use the Google Geolocation API. I have my key that tells me the latitude and longitude, I get the map of the exact location as in the image. But what I need is the map without the red destination marker.

I have this
I need this

I don't know if it is possible to do this with this API.

async function getApproximateLocation(apiKey) {
    try {
        const response = await fetch('https://www.googleapis.com/geolocation/v1/geolocate?key=' + apiKey, {
            method: 'POST'
        });
        const data = await response.json();
        return {
            latitude: data.location.lat,
            longitude: data.location.lng
        };
    } catch (error) {
        console.error('Error al obtener la ubicación aproximada:', error);
        throw error;
    }
}

.

const loc = userLocation ? `${userLocation.latitude},${userLocation.longitude}` : `${ipInfo.latitude},${ipInfo.longitude}`;
const mapUrl = `https://maps.google.com/maps?q=${loc}&z=12&output=embed`;
mapIframe.src = mapUrl;
mapContainer.style.display = 'block';

Upvotes: 1

Views: 300

Answers (2)

miguev
miguev

Reputation: 4855

There several different problems in your original approach that would need different solutions.

1. Exposing yourself to API key theft

Your JavaScript code, in particular the bit that sets the apiKey to a concrete value, can be seen by any user with a browser (and a little know-how). If your application is publicly accessible, crawlers may do the same.

Restricting API keys is not enough; the Geolocation API should not be queried from JavaScript.

Instead, you can use W3C Geolocation API as provided by browsers directly:

navigator.geolocation.getCurrentPosition()

2. Missing the accuracy property

Geolocation results depends on many variables, sometimes the result has a very high accuracy (tens or hundreds of meters) and sometimes the result has a very low accuracy (tens or hundreds of kilometers). They way you display the result above (z=12) assumes a constant size for all geolocation results, but one size does not exactly fit anybody.

Instead, you can use the accuracy property, e.g. as seen in this example.

3. Embedding a map does not allow hiding the marker

Your code above points to a Google Maps (not an API) with output=embed

https://maps.google.com/maps?q=37.4241173,-122.0915717&z=12&output=embed

This redirect to the actual Maps Embed API at https://www.google.com/maps/embed

In this API, Embedding a map does not support showing a place without a marker; because a place is represented by the marker.

But a Geolocation results is not a place; is instead an area (of varying size).

If you need an interactive map (one users can pan and zoom), follow the answer above and modify it to set the zoom level depending on the accuracy property.

If you don't need an interactive map, you could use instead the Maps Static API. This API support showing an area without any markers.

Upvotes: 1

Bench Vue
Bench Vue

Reputation: 9320

marker.setMap(null) This method removes the marker from the map. Setting the marker's map property to null effectively detaches the marker from the map, making it disappear immediately after being added.

More detain information in here enter image description here

This code can remove marker

const marker = new google.maps.Marker({
    position: { lat: location.latitude, lng: location.longitude },
    map: map
});

// Remove the marker immediately after it is added to the map
marker.setMap(null);

Demo

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Google Maps Example</title>
    <script>
        function loadGoogleMapsApi() {
            var apiKey = document.getElementById('api-key').value;
            var script = document.createElement('script');
            script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&callback=initializeMap`;
            document.head.appendChild(script);
        }

        document.addEventListener('DOMContentLoaded', loadGoogleMapsApi);
    </script>
    <script src="map.js"></script>
</head>
<body>
    <!-- Replace with your actual API key -->
    <input type="hidden" id="api-key" value="{API key}"> 
    <div id="map" style="height: 800px; width: 100%;"></div>
</body>
</html>

map.js

async function getApproximateLocation(apiKey) {
    try {
        const response = await fetch('https://www.googleapis.com/geolocation/v1/geolocate?key=' + apiKey, {
            method: 'POST'
        });
        const data = await response.json();
        return {
            latitude: data.location.lat,
            longitude: data.location.lng
        };
    } catch (error) {
        console.error('Error obtaining approximate location:', error);
        throw error;
    }
}

function initializeMap() {
    const apiKey = document.getElementById('api-key').value;

    getApproximateLocation(apiKey).then(location => {
        const mapOptions = {
            center: new google.maps.LatLng(location.latitude, location.longitude),
            zoom: 12
        };

        const map = new google.maps.Map(document.getElementById('map'), mapOptions);

        const marker = new google.maps.Marker({
            position: { lat: location.latitude, lng: location.longitude },
            map: map
        });

        // Remove the marker immediately after it is added to the map
        marker.setMap(null);

    }).catch(error => {
        console.error('Error initializing map:', error);
    });
}

Result

enter image description here

Upvotes: 1

Related Questions