DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

[JavaScript] How to Dynamically Create a URL to Open a Latitude and Longitude Location on Google Maps

Introduction

While building a map app using React and Superbase, I encountered a situation where I wanted to create a link to open a specific spot on Google Maps.

The Google Maps coordinate link format is useful for this.

Basic URL Structure

In Google Maps, you can open a location by specifying a latitude and longitude using the following syntax:

https://www.google.com/maps?q=<lat>,<lng>
Enter fullscreen mode Exit fullscreen mode

For example, if you want to display

Latitude: 49.2827

Longitude: -123.1207

https://www.google.com/maps?q=49.2827,-123.1207

Opening this link in a browser will display that location with a pin.

Dynamic Creation with JavaScript

When using variables in React, etc.,
construct the URL using a template literal.

const lat = 49.2827;
const lng = -123.1207;

const googleMapUrl = `https://www.google.com/maps?q=${lat},${lng}`;

console.log(googleMapUrl);
// → https://www.google.com/maps?q=49.2827,-123.1207
Enter fullscreen mode Exit fullscreen mode

Using a template literal (...),
you can embed the variable ${} within a string.

Example using React

For example, retrieving spot information from Supabase:

<a
href={`https://www.google.com/maps?q=${spot.latitude},${spot.longitude}`}
target="_blank"
rel="noopener noreferrer"
>
Open in Google Maps
</a>
Enter fullscreen mode Exit fullscreen mode

Writing it like this, clicking will open the location of the spot in Google Maps.

Top comments (0)