In the last blog post, we learned about geolocation and we learned to find the user's location and do all sorts of cool stuff with it. Today, we'll learn about Google Maps API and use it to display the user's location that we found with the help of the Geolocation API.
![]() |
Using Google Maps to enhance our geolocation power. |
Google Maps API - View Mode
For our purposes we're going to use the view mode of the google maps api. You can read more about it in the official docs.
To use the API, you have to have an iframe on your web page with the following URL in it:
https://www.google.com/maps/embed/v1/view ?key=API_KEY ¢er=37.4218,-122.0840Where, you'll have to replace API_KEY with your api key (obviously) which you can get from the instructions mentioned in the official docs. You'll also have to provide the latitude and the longitude to the center parameters.
Optional parameters:
- zoom: sets the zoom level of the map.
- maptype: can be roadmap (default), satellite.
- language
- region
Using it for our geolocation purposes
Now that we know to use Google Maps API let's use it to display a map pinpointing the user's location. Well, you already know how to find the user's location from the previous post on geolocation, so the only thing you'll have to learn today is to use the Maps API, here's how we do it:
if(navigator.geolocation){ navigator.geolocation.getCurrentPosition(showMap); } function showMap(position){ // The iframe object var ifrme = document.getElementById("iframe_id"); // Your API KEY var api_key = "****"; // It's not actually ****, // you must replace it with your key // Center coordinates var center = position.coords.latitude+"," +position.coords.longitude; // Manipulating the iframe var url = "https://www.google.com/maps/embed/v1/view?key=" +api_key+"¢er="+center; ifrme.src = url; }So what are you waiting for? Try it out now!
No comments:
Post a Comment