JSFiddle - React, Tailwind, and code Playground
HTML
<div id="map"></div>
<script
async
defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=beta"
></script>
CSS
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
JavaScript
let map
let infoWindow
const API_KEY = "AIzaSyBj5zfC9KuQwBmICZFDoL3hX_MxRvw73ec"
const INSIGHTS_API_URL =
"https://areainsights.googleapis.com/v1:computeInsights"
const PLACES_API_URL = "https://places.googleapis.com/v1/places:searchText"
// San Francisco ZIP codes for area mapping
const SF_ZIP_CODES = [
94102, 94103, 94104, 94105, 94107, 94108, 94109, 94110, 94111, 94112, 94114,
94115, 94116, 94117, 94118, 94121, 94122, 94123, 94124, 94127, 94129, 94130,
94131, 94132, 94133, 94134, 94158,
]
// Fetches Google Places API place ID for a given ZIP code
async function fetchPlaceIdForZip(zipCode) {
const searchQuery = `${zipCode} ZIP code San Francisco, CA`
try {
const response = await fetch(PLACES_API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Goog-Api-Key": API_KEY,
"X-Goog-FieldMask": "places.id",
},
body: JSON.stringify({
textQuery: searchQuery,
locationBias: {
rectangle: {
low: {
latitude: 37.708295,
longitude: -122.513642,
},
high: {
latitude: 37.832431,
longitude: -122.356499,
},
},
},
}),
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
const data = await response.json()
return {
zipCode,
placeId: data.places?.[0]?.id || null,
}
} catch (error) {
return { zipCode, placeId: null }
}
}
// Creates a mapping between ZIP codes and their corresponding Google Place IDs
async function buildZipToPlaceIdMap() {
const zipToPlaceId = new Map()
const results = await Promise.all(
SF_ZIP_CODES.map((zipCode) => fetchPlaceIdForZip(zipCode)),
)
results.forEach(({ zipCode, placeId }) => {
if (placeId) {
zipToPlaceId.set(zipCode, placeId)
}
})
return zipToPlaceId
}
// Initializes the Google Map and sets up data...