With this tutorial you’ll see how we can place a Google map with search box on your web page, and then get coordinates (i.e. latitude and longitude) based on where you click or where you drag and drop the marker into. The JavaScript API of Google Maps will help us achieve this.
This kind of map will be useful if you want to save coordinates from a Google map into your database. For example, if you’d like to save coordinates of a user-defined location, you can incorporate this map into your registration process — ask your users to point the marker to their location by clicking on the map or by dragging then dropping the marker.
There will be two types of icons in this map. First, a red default marker. Wherever you move it, we’ll get the coordinates that it points to. Second, white square markers which will appear to point to the location you searched for using the search box.
Map Demo
Try the map below — this is more or less how our map will look like later at the end of this tutorial. 🙂 Please read on and soon I’ll share the codes with you.
Get coordinates from Google Map
Latitude: Â Â Longitude:
Click on any point or drag the marker to get coordinates.
- Google map on a web page
- Search box for map
- Get map coordinates on click
- Get map coordinates on drag and drop of the marker
- Familiarity with HTML and JavaScript
- Internet connection
- Google account
- Development environment (I used XAMPP on Windows 7 for this)
- Code editor (I use Sublime Text)
But the tutorial does not include the following yet:
- Customized marker image
- Set map coordinates based on field value
- Google Developers Console monitoring
- Saving of coordinates to database
Get a key for Google Maps JavaScript API
Let’s begin by getting an API key for the Google map we’re about to embed.
Why get an API key?
Including a key in our API request lets us monitor our API usage in the Google Developers Console, lets us have per-key quota limits (instead of per-IP address), and lets Google contact us if there’s any issue regarding the application/project where we are using the map.
Instructions on getting API key for Google Maps
- Click here to go to Google Developers Console for registration of your application. You may choose to create a new project or use an existing one — it’s up to you. Skip step 2 if you want to use an existing project.
- Select “Create a new project” on the dropdown, then click Continue.
- Type the “Name” you want for this specific API key that we’re creating.
- Below the field for “Name”, there’s an optional field “Accept requests from these HTTP referrers (web sites)” but Google recommends that we fill this field too, especially when in production environment.You may leave this blank, but if you do, requests will be accepted from anywhere. What happens if requests are accepted from anywhere? Other websites may make a request using your API key and consume your quota.
- Click the “Create” button, and then you will see the API that has been generated for you. Copy the API key and save it. We’ll be using that soon.
Prepare codes
Let’s begin making a map that allows us to get coordinates on click or by drag and drop.
At the end of this post, I’ll provide a download link to the source code of the map. But before that, I’ll briefly show you the contents of the files.
index.php
Save as YOUR-FOLDER-PATH/index.php
. You may save it as .html too.
IMPORTANT: Replace [YOUR-API-KEY] with the API key that you saved earlier.
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 |
<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>Get coordinates from Google Map</title> <style> .map_container *{ font-family: roboto; } .map_container #pac-input { margin: 10px; padding: 5px; width: 330px; } </style> </head> <body> <h1>Get coordinates from Google Map</h1> <input id="pac-input" class="controls" type="text" placeholder="Search for a place here..."> <b>Latitude:</b> <input type="text" id="latitude" placeholder="latitude"> <b>Longitude:</b> <input type="text" id="longitude" placeholder="longitude"> <hr> <p>Click on any point or drag the marker to get coordinates.</p> <div id="map" style="width:500px; height:400px"></div> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=<strong>[YOUR-API-KEY]</strong>&sensor=false&libraries=places"></script> <script src="assets/js/google-map.js"></script> </body> </html> |
Snippets from a JavaScript file that we’ll use later for the map
The variables at the beginning of the JavaScript are what I think would most likely be configured by you, and some other global variables. If you want to disable the “drag and drop” function, set drag_and_drop
to false, and if you want to disable the placement of marker on click, set click_and_drop
to false. Set your desired default coordinates value to latitude
and longitude
. If you don’t like the icon I chose for results from the Search Box, you may change it. You may refer to Google Map icons for markers. To use an icon that you like, just copy the path to the icon set, then append the icon’s file name. You can also modify the zoom
value, depending on how close your view needs to be.
1 2 3 4 5 6 7 8 9 10 11 12 |
/** * Config */ var marker, map, drag_and_drop = true, // allow drag and drop of marker? click_and_drop = true, // allow click and drop of marker? latitude = 14.557023, // default latitude when map loads longitude = 121.015137, // default longitude when map loads search_icon_url = "http://maps.google.com/mapfiles/kml/pal4/icon26.png", // what to mark searched places with zoom = 17; // how close to zoom in |
Here’s the placeMarker
function. Pass the map coordinates to this function to place the marker into another location.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/** * Place marker on coordinates * @param {object} location {J: 14.557653862512797, M: 121.01658225059509} */ function placeMarker(location) { console.log(typeof location); if (marker === undefined){ marker = new google.maps.Marker({ position: location, map: map, animation: google.maps.Animation.DROP, }); } else{ marker.setPosition(location); } /** * Uncomment to set marker at center */ // map.setCenter(location); } |
This is the initialize()
function and would be the core function of our Google Map. I won’t explain the lines of code in this function anymore because there are already some comments between the lines of code.
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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
/** * Initialize Google Map */ function initialize() { var $latitude = document.getElementById('latitude'); var $longitude = document.getElementById('longitude'); $latitude.value = latitude; $longitude.value = longitude; var LatLng = new google.maps.LatLng(latitude, longitude); /** * Instantiate Map */ var mapOptions = { zoom: zoom, center: LatLng, panControl: false, zoomControl: false, scaleControl: true, draggableCursor: 'pointer', draggingCursor: 'crosshair', mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById('map'), mapOptions); /** * Instantiate marker */ var marker_setting = { position: LatLng, map: map, title: 'Drag and Drop' } if(drag_and_drop === true){ marker_setting.draggable = true; } marker = new google.maps.Marker(marker_setting); /** * Create the search box and link it to the UI element. */ var input = document.getElementById('pac-input'); var searchBox = new google.maps.places.SearchBox(input); map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); /** * Bias the SearchBox results towards current map's viewport. */ map.addListener('bounds_changed', function() { searchBox.setBounds(map.getBounds()); }); var markers = []; /** * [START region_getplaces] * Listen for the event fired when the user selects a prediction and retrieve * more details for that place. */ searchBox.addListener('places_changed', function() { var places = searchBox.getPlaces(); if (places.length == 0) { return; } // Clear out the old markers. markers.forEach(function(marker) { marker.setMap(null); }); markers = []; // For each place, get the icon, name and location. var bounds = new google.maps.LatLngBounds(); places.forEach(function(place) { var icon = { url: search_icon_url, size: new google.maps.Size(71, 71), origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(17, 34), scaledSize: new google.maps.Size(25, 25) }; // Create a marker for each place. markers.push(new google.maps.Marker({ map: map, icon: search_icon_url, title: place.name, position: place.geometry.location })); if (place.geometry.viewport) { // Only geocodes have viewport. bounds.union(place.geometry.viewport); } else { bounds.extend(place.geometry.location); } }); map.fitBounds(bounds); }); // [END region_getplaces] /** * Listen for click event, update marker location,update coordinates */ if(click_and_drop === true){ google.maps.event.addListener(map, 'click', function(event) { console.log(event.latLng.lat()); console.log(event.latLng.lng()); console.log('event.latLng:'); console.log(event.latLng); placeMarker(event.latLng); $latitude.value = event.latLng.lat(); $longitude.value = event.latLng.lng(); }); } /** * Listen for marker drag event and update coordinates */ if(drag_and_drop === true){ google.maps.event.addListener(marker, 'dragend', function(marker){ var latLng = marker.latLng; $latitude.value = latLng.lat(); $longitude.value = latLng.lng(); }); } } |
And finally, go ahead and initialize the Google Map on your web page.
1 2 3 4 |
/** * Fire the initialize function */ initialize(); |
Your map should now look like the one on my sample map at the top of this page.
Download source code: Google map where you can get coordinates on click or drag and drop
Remember to replace [YOUR-API-KEY]
in index.php
with the API key you retrieved earlier.
Source code: Get coordinates from Google Map on click or drag and drop (unknown, 371 hits)
Extract the files and move index.php
as well as the assets folder where you want. You can also turn it into an HTML file index.html
if you prefer not to run Apache for the .php
file. An easy way to edit the extension from php to html is through FileZilla’s folder browser.
Then view your index in a web browser. Your map should look like the one in my demo.
Comments? Suggestions?
Feel free to suggest anything that will improve this tutorial. 🙂
Great Script! Thanks a lot!
Only suggestion I have is, it would be great if the search would send back the coords as well …
Best, Bernd