Categories: CSSScriptWeb Design

Google Maps Location Picker: Get, Select & Save Lat/Lng in JS

location-picker is a lightweight JavaScript library that allows you to easily get Google Map location data in your web application.

It renders a Google map and lets users pin a specific spot to retrieve the exact coordinates (Latitude and Longitude) via click or idle position.

Perfect for forms that require a location picker.

Features:

  • Renders a Google Maps picker inside any target element.
  • Returns the selected latitude and longitude.
  • Accepts an element ID or direct HTMLElement reference.
  • Supports initial coordinates.
  • Can request the user’s current position.
  • Passes Google Maps options to the map instance.
  • Supports TypeScript projects with exported types.
  • Cleans up listeners and marker DOM in single page apps.

Use Cases:

  • Address forms can save exact delivery or service coordinates.
  • Store submissions can collect a map position from business owners.
  • Real estate forms can attach Lat/Lng data to listings.
  • Booking forms can let users choose pickup or meeting points.
  • Admin dashboards can edit location records on a map.

How to implement the Google Map Location Picker:

1. Install the package from npm.

# NPM
$ npm install location-picker

2. Load the Google Maps JavaScript API on the page. Replace the key with your own Google Maps API key.

<script src="https://maps.googleapis.com/maps/api/js?key=YouApiKeyHere"></script>

3. Create a map container.

<div id="map"></div>
<p>Selected position: <span id="selectedPosition">None</span></p>

4. Import the library and its stylesheet in your JavaScript bundle.

import { LocationPicker } from 'location-picker';
import 'location-picker/style.css';

5. Initialize the Location Picker.

const picker = new LocationPicker(
  'map',
  {
    setCurrentPosition: true,
    onLocationChange: function(position) {
      output.textContent = position.lat + ', ' + position.lng;
    }
  },
  {
    zoom: 15
  }
);

6. This example writes the selected coordinates into hidden form fields. Use this pattern for contact forms, booking forms, and listing submission forms.

<form id="locationForm">
  <div id="map"></div>
  <input id="latitude" name="latitude" type="hidden">
  <input id="longitude" name="longitude" type="hidden">
  <p>Current selection: <span id="preview">None</span></p>
  <button type="submit">Submit Location</button>
</form>
const latitude = document.getElementById('latitude');
const longitude = document.getElementById('longitude');
const preview = document.getElementById('preview');
const picker = new LocationPicker(
  document.getElementById('map'),
  {
    lat: 34.0522,
    lng: -118.2437,
    setCurrentPosition: false,
    onLocationChange: function(position) {
      latitude.value = position.lat;
      longitude.value = position.lng;
      preview.textContent = position.lat + ', ' + position.lng;
    }
  },
  {
    zoom: 14,
    streetViewControl: false,
    mapTypeControl: false
  }
);

7. Google Maps can use AdvancedMarkerElement when you load the marker library and provide a map ID. Set useAdvancedMarker to true in the picker options.

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY&libraries=marker"></script>
<div id="map"></div>
import { LocationPicker } from 'location-picker';
import 'location-picker/style.css';

const picker = new LocationPicker(
  'map',
  {
    useAdvancedMarker: true,
    onLocationChange: function(position) {
      console.log('New map position:', position);
    }
  },
  {
    mapId: 'YOUR_MAP_ID',
    zoom: 16
  }
);

8. All default options for the location picker.

  • setCurrentPosition (boolean): Requests the user’s current position by default. The library skips this step when you provide both lat and lng.
  • lat (number): Sets the initial latitude.
  • lng (number): Sets the initial longitude.
  • useAdvancedMarker (boolean): Uses Google Maps AdvancedMarkerElement when the marker library is available.
  • onLocationChange (function): Runs on each map idle event and receives the current { lat, lng } position.
  • mapOptions (google.maps.MapOptions): Passes Google Maps options to the internal google.maps.Map instance.

9. API methods.

// Returns the current marker position.
picker.getMarkerPosition();

// Moves the marker and map center to a new position.
picker.setLocation(41.8781, -87.6298);

// Requests the user's current position and resolves with Lat/Lng data.
picker.setCurrentPosition().then(function(position) {
  console.log(position.lat, position.lng);
});

// Removes event listeners and marker DOM.
picker.destroy();

TypeScript Usage:

import { LocationPicker } from 'location-picker';
import type { LatLng, LocationPickerOptions } from 'location-picker';
import 'location-picker/style.css';

const options: LocationPickerOptions = {
  setCurrentPosition: true,
  onLocationChange: function(position: LatLng) {
    console.log(position.lat, position.lng);
  }
};

const picker = new LocationPicker('map', options, { zoom: 15 });

Alternatives:

FAQ:

Q: Does location-picker require Google Maps?
A: Yes. The library uses the Google Maps JavaScript API, so your page needs a valid Google Maps API key.

Q: Can I use the old browser CDN file?
A: The v2 has removed UMD bundle. Use ESM or CommonJS for the current package version.

Q: How do I get the selected latitude and longitude?
A: Call picker.getMarkerPosition() or use the onLocationChange callback to receive { lat, lng }.

Q: Why does the map not appear?
A: Check the Google Maps API key, load the Google Maps script before creating the picker, and give the map container a visible height.

Q: Can I use AdvancedMarkerElement?
A: Yes. Load the Google Maps marker library, provide a mapId, and set useAdvancedMarker: true.

Changelog:

05/11/2026

  • Updated for Location Picker v2

v2.0.0 (04/12/2026)

  • useAdvancedMarker option — use Google Maps AdvancedMarkerElement when available (falls back to CSS-pin overlay)
  • onLocationChange(pos) option — callback fired on map idle
  • destroy() method — removes listeners and overlay DOM
  • Named export: import { LocationPicker } from ‘location-picker’
  • Exported types: LocationPickerOptions, LatLng
  • setCurrentPosition() now returns Promise<LatLng> instead of fire-and-forget
  • Dropped UMD bundle — ESM (dist/index.mjs) + CJS (dist/index.cjs) only

The post Google Maps Location Picker: Get, Select & Save Lat/Lng in JS appeared first on CSS Script.

rssfeeds-admin

Share
Published by
rssfeeds-admin

Recent Posts

Add an Floating Accessibility Panel via Web Component – Open Overlay

Open Overlay is a vanilla JavaScript Web Component that adds an accessibility settings widget to…

1 hour ago

10 Best Full Disk Encryption Tools in 2026

Full Disk Encryption (FDE) is a security feature that encrypts the entire contents of a…

2 hours ago

Top 10 Best Interactive Malware Analysis Tools in 2026

As we navigate through 2026, the cybersecurity landscape has never been more complex. Threat actors…

2 hours ago

ODINI Malware Uses CPU Magnetic Emissions to Breach Faraday-Shielded Air-Gapped Computers

ODINI is a sophisticated proof-of-concept malware capable of extracting sensitive information from air-gapped computers protected…

2 hours ago

Sail Drones Deployed on Great Lakes for First Time in 2026 Summer Patrols

CHICAGO, IL (WOWO) A new era of maritime monitoring is coming to the Great Lakes…

2 hours ago

Rural Animal Shelters Could Gain Easier Access to USDA Grants Under New Farm Bill Provision

INDIANAPOLIS, IND. (WOWO) Rural animal shelters across the country could soon see expanded access to…

2 hours ago

This website uses cookies.