Google Maps API – Location Picker Example

This is a simple tutorial on how to allow users to select a location via the Google Maps JavaScript API.

Overview of how the location picker will work:

  1. The map is loaded.
  2. The user plots a location marker by clicking on the map.
  3. If the marker is dragged or a different location is clicked, we change the position of the marker.
  4. Whenever the position of the marker is changed, we grab the latest latitude / longitude values.
  5. We store the latitude / longitude values in text fields so that we can easily save them as part of a form.


As you can see, I have created a basic HTML page with a map canvas and a form. The actual logic will be contained in a JavaScript file called map.js.

Drill-down of the code above (reading the comments in the code will make more sense):

  • After we initialized the map, we added a “click” event listener. As the name suggests, this event listener will listen for any clicks that are made on the map.
  • If there is a click on the map, we retrieve the location that the click occurred on.
  • We also set up a “dragend” event listener on the marker. This listener tells us when the marker has been dragged to a new location by the user.
  • Both of these event listeners call the markerLocation function, which stores the latitude and longitude values of the marker’s current location in our text fields.

Once the lat / lng values have been stored inside our text fields, we can easily save them by inserting them into a database.

Facebook Comments