Welcome folks today in this blog post we will be using the google maps
and reverse geocoding
api to add red markers
and popup window
and show address in it in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to go to google cloud console
and get your own api key
and enable the google maps javascript
api and also reverse geocoding
api as shown below
Now we need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
<html xmlns="http://www.w3.org/1999/xhtml"> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <head> <script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false&key=##yourapikey##"></script> <script type="text/javascript"> window.onload = function () { var mapOptions = { center: new google.maps.LatLng(21.0000, 78.0000), zoom: 5, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions); //Attach click event handler to the map. google.maps.event.addListener(map, 'click', function (e) { //Determine the location where the user has clicked. var location = e.latLng; //Create a marker and placed it on the map. var marker = new google.maps.Marker({ position: location, map: map }); let lat = marker.getPosition().lat() let lng = marker.getPosition().lng() let contentAdd = "" $.ajax({ method:'POST', url:`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&sensor=true&key=##yourapikey##`, success:function(data){ console.log(data) contentAdd = data.results[0].formatted_address } }) //Attach click event handler to the marker. google.maps.event.addListener(marker, "click", function (e) { var infoWindow = new google.maps.InfoWindow({ content: contentAdd }); infoWindow.open(map, marker); }); }); }; </script> </head> <body> <div id="dvMap" style="width:100%; height: 500px"> </div> </body> </html> |
As you can see we have the div
section where we will be displaying the map and we have attached the custom
css in which we are providing the width
and height
property. And here you need to replace the api key
as shown above.