Skip to content

Instantly share code, notes, and snippets.

@khatthaphone
Created April 24, 2024 09:25
Show Gist options
  • Save khatthaphone/4edb56f3753b17d7cad45cfd1f9e7d2a to your computer and use it in GitHub Desktop.
Save khatthaphone/4edb56f3753b17d7cad45cfd1f9e7d2a to your computer and use it in GitHub Desktop.
Get Coordinate (Lat, Lng) from Google Maps Short URL
import cors from 'cors'
import express, { json, urlencoded } from 'express'
import puppeteer from 'puppeteer'
const app = express()
app.use(cors())
app.use(json({ inflate: true }))
app.use(urlencoded({ extended: true }))
app.post('/get-latlng-from-url', async (req, res) => {
const url: string = req.body['url']
const browser = await puppeteer.launch({
headless: process.env.NODE_ENV == 'production' ? true : false
})
const page = await browser.newPage()
await page.goto(url)
await page.waitForNetworkIdle()
const currentUrl = page.url()
const regex = /@(-?\d+(\.\d+)?),(-?\d+(\.\d+)?)/
const result = currentUrl.match(regex)
if (result) {
const coordinates = `@${result[1]},${result[3]}`
console.log(coordinates)
return res.json({
success: true,
lat: result[1],
lng: result[3],
fullUrl: currentUrl
})
} else {
console.log('Coordinates not found')
return res.json({
success: false,
message: 'Coordinates not found'
})
}
})
app.listen(3000, () => {
console.log('Listening on port 3000')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment