Implement draggable Google Map on website with fixed pin at center

To make the map draggable with one finger, particularly for mobile devices, you need to ensure that the map is responsive to touch gestures. The Google Maps JavaScript API supports touch gestures by default, but sometimes additional CSS can help ensure optimal touch functionality, especially when there are other touch-based interactions on the page.

<body onload="initMap()">
    <h1>Google Map with Fixed Center Marker and Search Box</h1>
    <input id="pac-input" class="controls" type="text" placeholder="Search Box">
    <div id="map"></div>
    <br>
    <label>Latitude: </label>
    <input type="text" id="lat" readonly>
    <br>
    <label>Longitude: </label>
    <input type="text" id="lng" readonly>
</body>

 

Use Google Map API to fetch the data along with latitude and longitude.

https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places

You need to include the Map script to fetch the data from Google

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>

Now, you must initialize the variables like let map, marker, searchBox;

After initializing the variables, initialize the map with initializeMap()

function.

function initializeMap(location) {
    // Create the map
    map = new google.maps.Map(document.getElementById("map"), {
        center: location,
        zoom: 12,
        gestureHandling: 'greedy' // Ensures the map is draggable with one finger
    });

    // Create a fixed marker at the center of the map
    marker = new google.maps.Marker({
        position: location,
        map: map
    });

    // Create the search box and link it to the UI element
    const input = document.getElementById('pac-input');
    searchBox = new google.maps.places.SearchBox(input);

    // Bias the SearchBox results towards current map's viewport
    map.addListener('bounds_changed', () => {
        searchBox.setBounds(map.getBounds());
    });

    // Listen for the event fired when the user selects a prediction and retrieve
    // more details for that place
    searchBox.addListener('places_changed', () => {
        const places = searchBox.getPlaces();

        if (places.length == 0) {
            return;
        }

        // Get the place details from the user input
        const place = places[0];
        if (!place.geometry) {
            console.log("Returned place contains no geometry");
            return;
        }

        // Move the map to the selected place
        map.panTo(place.geometry.location);
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setZoom(17);  // Adjust zoom level as needed
        }

        // Update the latitude and longitude values
        updateLatLng();
    });

    // Update the latitude and longitude values when the map is moved
    map.addListener('center_changed', () => {
        updateLatLng();
    });

    // Function to update the latitude and longitude values based on the map's center
    function updateLatLng() {
        const center = map.getCenter();
        document.getElementById("lat").value = center.lat();
        document.getElementById("lng").value = center.lng();
        marker.setPosition(center); // Ensure marker stays at the center
    }

    // Initial update of the latitude and longitude values
    updateLatLng();
}

While initializing the map you can override default gesture of dragging the map with two fingers in mobile viewport. To enable one finger drag gesture in Google map you need to add draggable: false

attribute.

function initializeMap(location) {
    // Create the map
    map = new google.maps.Map(document.getElementById("map"), {
        center: location,
        zoom: 12,
        gestureHandling: 'greedy' // Ensures the map is draggable with one finger
    });

    // Create a fixed marker at the center of the map
    marker = new google.maps.Marker({
        position: location,
        map: map,
        draggable: false
    });

    // Create the search box and link it to the UI element
    const input = document.getElementById('pac-input');
    searchBox = new google.maps.places.SearchBox(input);

    // Bias the SearchBox results towards current map's viewport
    map.addListener('bounds_changed', () => {
        searchBox.setBounds(map.getBounds());
    });

    // Listen for the event fired when the user selects a prediction and retrieve
    // more details for that place
    searchBox.addListener('places_changed', () => {
        const places = searchBox.getPlaces();

        if (places.length == 0) {
            return;
        }

        // Get the place details from the user input
        const place = places[0];
        if (!place.geometry) {
            console.log("Returned place contains no geometry");
            return;
        }

        // Move the map to the selected place
        map.panTo(place.geometry.location);
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setZoom(17);  // Adjust zoom level as needed
        }

        // Update the latitude and longitude values
        updateLatLng();
    });

    // Update the latitude and longitude values when the map is moved
    map.addListener('center_changed', () => {
        updateLatLng();
    });

    // Function to update the latitude and longitude values based on the map's center
    function updateLatLng() {
        const center = map.getCenter();
        document.getElementById("lat").value = center.lat();
        document.getElementById("lng").value = center.lng();
        marker.setPosition(center); // Ensure marker stays at the center
    }

    // Initial update of the latitude and longitude values
    updateLatLng();
}

 

After initializing Google map you need to implement initMap()

function which will be called onload the body element.

function initMap() {
    // Check if Geolocation is supported
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
            const userLocation = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };

            initializeMap(userLocation);
        }, () => {
            // If user denies Geolocation or it's not available, fall back to a default location
            const defaultLocation = { lat: 40.7128, lng: -74.0060 }; // New York City
            initializeMap(defaultLocation);
        });
    } else {
        // Browser doesn't support Geolocation, fall back to a default location
        const defaultLocation = { lat: 40.7128, lng: -74.0060 }; // New York City
        initializeMap(defaultLocation);
    }
}

Here is the working link of the Google map functionality