To add Google Maps in an ASP.NET Core web application, you can follow these steps:
- Get an API Key: First, you need to get a Google Maps API key. You can get this by following the instructions on the Google Maps Platform website.
- Install Google Maps JavaScript API: Next, you need to install the Google Maps JavaScript API using NPM. You can do this by running the following command in the Package Manager Console:
Install-Package GoogleMapsJS
- Add Google Maps script to your HTML file: You need to add the Google Maps JavaScript API script to your HTML file. You can do this by adding the following code to your _Layout.cshtml file:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
Note that you should replace YOUR_API_KEY with the actual API key you obtained in step 1.
- Create a View: Create a new view or modify an existing one to include a container where the map will be displayed. For example:
<div id="map" style="height: 400px;"></div>
- Initialize the Map: Then you need to initialize the map by adding the following code to your JavaScript file:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 51.509865, lng: -0.118092 },
zoom: 8
});
}
Note that the center property specifies the initial center of the map, and the zoom property specifies the initial zoom level.
- Call the initMap function: Finally, you need to call the initMap function when the page is loaded. You can do this by adding the following code to your HTML file:
<script>
initMap();
</script>
This will initialize the map when the page is loaded.
Recommendation:
Protect your API key : In order to protect your account from unwanted malicious usage, Google recommend restricting your Google Maps Platform API key.