I built the API behind a ride-booking chatbot. A passenger tells the bot where they are and where they are going, and the easiest way for them to do that is to paste a Google Maps link into the chat. The trips table wants a latitude,longitude string. A pasted link is not that. Sometimes it is a short link with no coordinates in it at all.
To get coordinates from a Google Maps link in Node.js without a geocoding API, I do three things in order. I request the link with Axios and let it follow redirects until it reaches the long URL. I run that URL through a list of regular expressions, one per link shape, and take the first match. If the URL still has no coordinates, I search the HTML of the returned page for them. The whole resolver is one file of about 110 lines with one export, getCoordinates(url), which returns a "lat,lng" string or null.
What a Google Maps share link looks like when it reaches the server
The links I handled fall into three groups:
- Short links. A short link is a compact URL that carries only an id and redirects to the real one. The ones I saw were on
maps.app.goo.glandgoo.gl/maps. - Full links. These already contain the position, usually after an
@, as inhttps://www.google.com/maps/@12.345678,98.765432,15z. - Place links. These name a place in the path,
/maps/place/Some+Place/..., and carry the position either after an@or inside adata=segment as!3d12.345678!4d98.765432.
So there are two separate problems: getting from a short link to a long one, and reading a coordinate pair out of whatever the long one turns out to be.
The exported function handles them in that order and is short. It strips all whitespace, so a pasted link with a stray space or line break still works. Then it decides whether the string needs a network request at all.
async function getCoordinates(url) {
url = url.replace(/\s/g, '');
if (url.includes("maps.app.goo.gl") || url.includes("goo.gl") ||
url.includes("maps.google") || url.includes("google.com/maps")) {
url = await resolveShortUrl(url);
}
return extractCoordinates(url);
}
resolveShortUrl always returns a string that the pattern list can read. It never returns coordinates itself. When it finds a pair in the page, it wraps the pair into a synthetic https://www.google.com/maps/@lat,lng URL. That keeps one function in charge of parsing, and the resolver only has to produce something that function understands.
Eleven regex patterns for Google Maps URL formats
extractCoordinates holds an array of eleven patterns and returns the first one that matches. Each pattern has two capture groups, latitude then longitude, and each requires a decimal point in both numbers.
const patterns = [
/data=!4m2!3m1!1s(?:.*?)!3d(-?\d+\.\d+)!4d(-?\d+\.\d+)/,
/!3d(-?\d+\.\d+)!4d(-?\d+\.\d+)/,
/@(-?\d+\.\d+),(-?\d+\.\d+)/,
/[?&]q=(-?\d+\.\d+),(-?\d+\.\d+)/,
/place\/[^\/]+\/@(-?\d+\.\d+),(-?\d+\.\d+)/,
/dir\/(-?\d+\.\d+),(-?\d+\.\d+)/,
/ll=(-?\d+\.\d+),(-?\d+\.\d+)/,
/query=(-?\d+\.\d+),(-?\d+\.\d+)/,
/center=(-?\d+\.\d+),(-?\d+\.\d+)/,
/"lat":(-?\d+\.\d+),"lng":(-?\d+\.\d+)/,
/\{"latitude":(-?\d+\.\d+),"longitude":(-?\d+\.\d+)\}/
];
In order, they cover:
- the mobile share form, a
data=!4m2!3m1!1s...segment followed by!3dand!4d - a bare
!3d<lat>!4d<lng>pair anywhere in the URL @<lat>,<lng>- a
q=<lat>,<lng>query parameter place/<name>/@<lat>,<lng>dir/<lat>,<lng>, the start of a directions linkll=<lat>,<lng>, used by embedded mapsquery=<lat>,<lng>center=<lat>,<lng>"lat":<lat>,"lng":<lng>{"latitude":<lat>,"longitude":<lng>}
The order is the priority. The !3d and !4d patterns come before @. In the place links I handled, the value after @ was the centre of the map view and the !3d!4d pair was the pin, and for a pickup point I want the pin. The loop itself is five lines:
for (const pattern of patterns) {
const match = url.match(pattern);
if (match) {
return `${match[1]},${match[2]}`;
}
}
return null;
Following short link redirects with Axios
A redirect is a response that tells the client to request a different URL. Axios follows redirects by default in Node.js, so resolving a short link is a GET request plus reading where it ended up. For maps.app.goo.gl links the request looks like this (the User-Agent string is shortened here):
const response = await axios.get(shortUrl, {
maxRedirects: 15,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ... Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Upgrade-Insecure-Requests': '1',
},
validateStatus: function (status) {
return status >= 200 && status < 400;
},
timeout: 10000,
});
Four settings matter. maxRedirects allows up to 15 hops. The headers are the ones a desktop browser sends, because I wanted the HTML page a person would get. validateStatus treats any status from 200 to 399 as success, so a 3xx response that ends the chain is not thrown as an error. And the request gives up after 10 seconds.
The final address is on the underlying Node response: response.request.res.responseUrl. If nothing better is found in the page, that is what the function returns, falling back to the original link if it is missing.
Every other Google link goes through a second request with a mobile Safari User-Agent and maxRedirects: 10. That branch has one extra rule. If the final URL is on preview.app.goo.gl, it returns the original link instead, because I did not treat that address as a map URL.
Falling back to the HTML of the returned page
Sometimes the chain ends at a URL with no coordinates in it. The page that comes back can still contain them, so before giving up on the response I search its body. For maps.app.goo.gl there are two checks:
if (response.data) {
// Check meta tags
const metaMatch = response.data.match(/<meta[^>]*content="([^"]*@-?\d+\.\d+,-?\d+\.\d+[^"]*)"[^>]*>/i);
if (metaMatch) return metaMatch[1];
// Check script tags
const scriptMatch = response.data.match(/window\.APP_INITIALIZATION_STATE[^]*?(-?\d+\.\d+),(-?\d+\.\d+)/);
if (scriptMatch) return `https://www.google.com/maps/@${scriptMatch[1]},${scriptMatch[2]}`;
}
return response.request.res.responseUrl || shortUrl;
The first looks for a <meta> tag whose content attribute holds an @lat,lng pair and returns that whole attribute value, which is itself a link the pattern list can read. The second finds the window.APP_INITIALIZATION_STATE assignment in a script tag and takes the first pair of comma-separated decimals after it. [^]*? means "any characters, including line breaks, as few as possible".
The second branch does the same job with two lists. Four patterns look for a pair in the body: @lat,lng, !3d!4d, "lat":…,"lng":…, and a bare [lat,lng] array. If none match, three more look for a link to follow: a window.location.replace("...") call, or an href pointing at https://www.google.com/maps or https://goo.gl/maps.
The whole resolver sits in one try. On any failure it logs and returns the original link, and the pattern list gets its chance at that.
Where the resolver sits in the trip endpoint
The Express controller that creates a trip accepts each location in three forms, and runs the same function over the pickup and the destination:
const parseLocation = (location) => {
try {
if (typeof location === 'string' && location.includes('latitude') && location.includes('longitude')) {
const locationObj = JSON.parse(location);
return `${locationObj.latitude},${locationObj.longitude}`;
}
if (
typeof location === 'string' &&
(location.includes('google.com/maps') || location.includes('goo.gl/maps'))
) {
return getCoordinates(location);
}
return location;
} catch (error) {
return location;
}
};
A location that arrives as a JSON string with latitude and longitude keys is read directly. A Google Maps link goes to the resolver. Anything else is kept as typed text. If a link resolves to null, the endpoint answers 400 with "Invalid location format provided." and no trip is created.
Trade-offs and what I would improve
- Range checks. The patterns accept any two decimals. The bare
[lat,lng]pattern and the "first pair after the state variable" pattern are the loosest. I would validate that latitude is within ±90 and longitude within ±180 before accepting a match. - One timeout for both requests. The 10 second timeout is set on the first request. I would set it on the second as well.
- Tests from real links. The patterns grew over several commits as I met new link shapes. A fixture file of sample links with expected output would make the ordering safe to change.
Takeaways
- A short Maps link has no coordinates in it, so the first step is always an HTTP request that follows redirects.
- Keep one function that parses coordinates and make every other step return a string that function can read.
- Order the patterns by which value you trust most: the pin (
!3d!4d) before the view centre (@). - When the final URL has nothing useful, the response body may, so check it before giving up.
- Return
nullfor a link you cannot read and let the endpoint reject it, instead of saving a guess.