Google maps are used for showing maps of locations, adding markers, showing custom location data related to region, places etc.
Here are the simple steps for showing Google map on a web page
- Create HTML Page
- Add a map
- Get API key from Google developer console
Create HTML page – On first step, we need to create an html page. In the html page, we will have a div with an id that will be passed to the Google map script. Here is the sample html
<!DOCTYPE html>
<html>
<head>
<style>
#map {
width: 100%;
height: 200px;
}
</style>
</head>
<body>
<h3>Google Maps</h3>
<div id="map"></div>
</body>
</html>
In the above html, there are few things to notice.
First is that we have created a div with the id map. Then we have a style for this div. This style is important as in order to show a map, we must define the height of map otherwise it does not display.
Add a map: - After creating the html, now we need to add the map. For this, we will need to use JavaScript. Here is the sample code
<!DOCTYPE html>
<html>
<head>
<style>
#map {
width: 100%;
height: 200px;
}
</style>
</head>
<body>
<h3>Google Maps</h3>
<div id="map"></div>
<script>
function initMap() {
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv, {
center: {lat: 44.540, lng: -78.546},
zoom: 8
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
In above html, we have added javascript initMap method. This method is used for initializing map data. In this method, first we are getting the map div then we are initializing the map api. Here we are passing mapdiv and center position. Center position tells the map as to where should be the focus of map. Zoom is used for showing the mam in zoomed manner.
Other that initMap method, we are also adding reference to the google map api js reference.
<script
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
The script will
load the API from the specified URL.
The callback
parameter executes the initMap
function after the API is completely loaded.
In the API url, we are also passing key parameter. This key parameter requires API key from google developer project.
Get API key from Google developer console: - Please go through the tutorial here
https://developers.google.com/identity/sign-in/web/devconsole-project
After creating the project, you will have the API key. Replace the key parameter of script url with your projects api key and you will be able to render the map.
0 Comment(s)