Simple Location Picker With JavaScript And Google Maps

Category: Javascript | March 31, 2018
Author: cyphercodes
Views Total: 1,519
Official Page: Go to website
Last Update: March 31, 2018
License: MIT

Preview:

Simple Location Picker With JavaScript And Google Maps

Description:

A simple location picker library that renders a Google Maps on the webpage and allows the user to pick a specific location based on the click or idle position.

How to use it:

Include the location-picker library and Google Maps JavaScript API on the page.

<script src="https://maps.googleapis.com/maps/api/js?key=YouApiKeyHere"></script>
<script src="/dist/location-picker.min.js"></script>

Create a placeholder element in which you want to render the Google Map.

<div id="map"></div>

Initialize the Location Picker.

var map = document.getElementById('map');

var instance = new locationPicker(map, {
    // picker options
  }, {
    // Google Maps Options
});

Listen to button onclick event, get current location and show it in HTML.

<button id="confirmPosition">Confirm Position</button>
<p>On click position: <span id="onClickPositionView"></span></p>
var confirmBtn = document.getElementById('confirmPosition');
var onClickPositionView = document.getElementById('onClickPositionView');

confirmBtn.onclick = function () {
  var location = lp.getMarkerPosition();
  onClickPositionView.innerHTML = 'The chosen location is ' + location.lat + ',' + location.lng;
};

Listen to map idle event, listening to idle event more accurate than listening to ondrag event. And then get current location and show it in HTML.

<p>On idle position: <span id="onIdlePositionView"></span></p>
google.maps.event.addListener(lp.map, 'idle', function (event) {
  var location = lp.getMarkerPosition();
  onIdlePositionView.innerHTML = 'The chosen location is ' + location.lat + ',' + location.lng;
});

All default options for the location picker.

var instance = new locationPicker(map, {

    // latitude
    lat: 45.5017,

    // longitude
    lng: -73.5673,

    // auto try and detect and set the marker to the the current user's location
    setCurrentPosition: true 
    
  }, {
    // Google Maps Options
});

You Might Be Interested In:


Leave a Reply