Building an Interactive Location Selector with Google Maps in ASP.NET MVC

Discover how to build a fully functional location selector feature for your ASP.NET MVC application using Google Maps API.

Introduction

This article provides a comprehensive, step-by-step guide to integrating Google Maps, allowing users to click on a map, select a location, and store it for future reference. From setting up Google Maps API to implementing JavaScript for map integration and handling user interactions, you'll find detailed instructions to create an interactive mapping feature. Additionally, learn how to seamlessly integrate database operations to store selected locations and retrieve them for display.

To achieve the functionality in ASP.NET MVC using Google Maps API, you can follow these steps.

1. Set up Google Maps API

Obtain a Google Maps API key from the Google Cloud Console and enable the necessary APIs (Maps JavaScript API, Geocoding API) for your project.

2. Create MVC Controller and Views

  • Create a controller with actions to handle the requests.
  • Create views for displaying the map, capturing the location, and displaying stored locations.

3. Implement JavaScript for Maps Integration

  • Use JavaScript to integrate Google Maps into your view.
  • Allow users to click on the map to select a location.
  • Retrieve the latitude and longitude of the selected location.
  • Display the selected location on the map.

4. Store Selected Location

  • When the user submits the selected location, send the latitude and longitude to the server.
  • Store the location in your database along with any additional information you want to associate with it.

5. Retrieve and Display Stored Locations

  • When the user wants to view stored locations, retrieve them from the database.
  • Display the stored locations as clickable links.
  • When a user clicks on a location link, display the location on the map.

Here's a basic example of how you can implement this.

Controller

public class LocationController : Controller
{
    public ActionResult Index()
    {
        // Display map for selecting location
        return View();
    }

    [HttpPost]
    public ActionResult SaveLocation(double latitude, double longitude, string locationName)
    {
        // Save the location in your database
        // Redirect to a success page or back to the map view
        return RedirectToAction("Index"); // Example redirection to Index action
    }

    public ActionResult DisplayLocations()
    {
        // Retrieve stored locations from the database
        // Display a view with clickable links to the stored locations
        return View();
    }
}

View (Index. cshtml)

<!-- Display Google Map -->
<div id="map" style="height: 400px; width: 100%;"></div>

<!-- Button to submit selected location -->
<button id="submitLocation">Submit Location</button>

<script>
    function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: { lat: -34.397, lng: 150.644 },
            zoom: 8
        });

        var marker;

        // Add click event listener to get selected location
        map.addListener('click', function (e) {
            var latitude = e.latLng.lat();
            var longitude = e.latLng.lng();
            
            // Clear previous marker
            if (marker) {
                marker.setMap(null);
            }

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

        // Event listener for submit button
        document.getElementById('submitLocation').addEventListener('click', function () {
            // Check if marker is defined
            if (marker) {
                // Get selected location data and submit to server
                var latitude = marker.getPosition().lat();
                var longitude = marker.getPosition().lng();
                var locationName = ""; // You may prompt the user for a name
                // Send latitude, longitude, and locationName to the server using AJAX
            } else {
                alert("Please select a location on the map.");
            }
        });
    }
</script>

<!-- Load Google Maps API -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>