Integrate interactive maps and geolocation features in Google Antigravity with Mapbox and Google Maps.
# Maps and Geolocation for Google Antigravity
Add interactive maps, geolocation services, and location-based features to your Google Antigravity applications using Mapbox and native geolocation APIs.
## Mapbox Setup and Basic Map
```typescript
// components/maps/MapContainer.tsx
"use client";
import { useRef, useEffect, useState } from "react";
import mapboxgl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";
mapboxgl.accessToken = process.env.NEXT_PUBLIC_MAPBOX_TOKEN!;
interface MapContainerProps {
center?: [number, number];
zoom?: number;
markers?: Array<{ lng: number; lat: number; title: string; color?: string }>;
onMarkerClick?: (marker: { lng: number; lat: number; title: string }) => void;
}
export function MapContainer({ center = [-74.006, 40.7128], zoom = 12, markers = [], onMarkerClick }: MapContainerProps) {
const mapContainer = useRef<HTMLDivElement>(null);
const map = useRef<mapboxgl.Map | null>(null);
const [loaded, setLoaded] = useState(false);
useEffect(() => {
if (map.current || !mapContainer.current) return;
map.current = new mapboxgl.Map({
container: mapContainer.current,
style: "mapbox://styles/mapbox/dark-v11",
center,
zoom,
});
map.current.addControl(new mapboxgl.NavigationControl(), "top-right");
map.current.addControl(new mapboxgl.GeolocateControl({
positionOptions: { enableHighAccuracy: true },
trackUserLocation: true,
showUserHeading: true,
}));
map.current.on("load", () => setLoaded(true));
return () => {
map.current?.remove();
map.current = null;
};
}, [center, zoom]);
useEffect(() => {
if (!map.current || !loaded) return;
// Clear existing markers
const existingMarkers = document.querySelectorAll(".mapboxgl-marker");
existingMarkers.forEach((m) => m.remove());
// Add new markers
markers.forEach((markerData) => {
const el = document.createElement("div");
el.className = "custom-marker";
el.style.backgroundColor = markerData.color || "#3b82f6";
el.style.width = "24px";
el.style.height = "24px";
el.style.borderRadius = "50%";
el.style.border = "3px solid white";
el.style.cursor = "pointer";
const marker = new mapboxgl.Marker(el)
.setLngLat([markerData.lng, markerData.lat])
.setPopup(new mapboxgl.Popup({ offset: 25 }).setHTML(`<h3>${markerData.title}</h3>`))
.addTo(map.current!);
if (onMarkerClick) {
el.addEventListener("click", () => onMarkerClick(markerData));
}
});
}, [markers, loaded, onMarkerClick]);
return <div ref={mapContainer} className="map-container" style={{ width: "100%", height: "400px" }} />;
}
```
## Geolocation Hook
```typescript
// hooks/useGeolocation.ts
import { useState, useEffect, useCallback } from "react";
interface GeolocationState {
latitude: number | null;
longitude: number | null;
accuracy: number | null;
heading: number | null;
speed: number | null;
timestamp: number | null;
error: GeolocationPositionError | null;
loading: boolean;
}
interface UseGeolocationOptions {
enableHighAccuracy?: boolean;
timeout?: number;
maximumAge?: number;
watch?: boolean;
}
export function useGeolocation(options: UseGeolocationOptions = {}) {
const { enableHighAccuracy = true, timeout = 10000, maximumAge = 0, watch = false } = options;
const [state, setState] = useState<GeolocationState>({
latitude: null,
longitude: null,
accuracy: null,
heading: null,
speed: null,
timestamp: null,
error: null,
loading: true,
});
const onSuccess = useCallback((position: GeolocationPosition) => {
setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
accuracy: position.coords.accuracy,
heading: position.coords.heading,
speed: position.coords.speed,
timestamp: position.timestamp,
error: null,
loading: false,
});
}, []);
const onError = useCallback((error: GeolocationPositionError) => {
setState((prev) => ({ ...prev, error, loading: false }));
}, []);
useEffect(() => {
if (!navigator.geolocation) {
setState((prev) => ({ ...prev, error: { code: 0, message: "Geolocation not supported" } as GeolocationPositionError, loading: false }));
return;
}
const geoOptions = { enableHighAccuracy, timeout, maximumAge };
if (watch) {
const watchId = navigator.geolocation.watchPosition(onSuccess, onError, geoOptions);
return () => navigator.geolocation.clearWatch(watchId);
} else {
navigator.geolocation.getCurrentPosition(onSuccess, onError, geoOptions);
}
}, [enableHighAccuracy, timeout, maximumAge, watch, onSuccess, onError]);
return state;
}
```
## Location Search with Geocoding
```typescript
// components/maps/LocationSearch.tsx
"use client";
import { useState, useCallback, useRef } from "react";
import debounce from "lodash.debounce";
interface SearchResult {
id: string;
place_name: string;
center: [number, number];
}
export function LocationSearch({ onSelect }: { onSelect: (result: SearchResult) => void }) {
const [query, setQuery] = useState("");
const [results, setResults] = useState<SearchResult[]>([]);
const [loading, setLoading] = useState(false);
const searchPlaces = useCallback(
debounce(async (searchQuery: string) => {
if (searchQuery.length < 3) {
setResults([]);
return;
}
setLoading(true);
try {
const response = await fetch(
`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(searchQuery)}.json?access_token=${process.env.NEXT_PUBLIC_MAPBOX_TOKEN}&limit=5`
);
const data = await response.json();
setResults(data.features || []);
} catch (error) {
console.error("Geocoding error:", error);
} finally {
setLoading(false);
}
}, 300),
[]
);
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setQuery(e.target.value);
searchPlaces(e.target.value);
};
return (
<div className="location-search">
<input type="text" value={query} onChange={handleInputChange} placeholder="Search for a location..." className="search-input" />
{loading && <div className="loading-spinner">Searching...</div>}
{results.length > 0 && (
<ul className="search-results">
{results.map((result) => (
<li key={result.id} onClick={() => { onSelect(result); setQuery(result.place_name); setResults([]); }} className="search-result-item">
{result.place_name}
</li>
))}
</ul>
)}
</div>
);
}
```
## Distance Calculation Utility
```typescript
// lib/geo-utils.ts
export function calculateDistance(lat1: number, lon1: number, lat2: number, lon2: number): number {
const R = 6371; // Earth radius in km
const dLat = toRad(lat2 - lat1);
const dLon = toRad(lon2 - lon1);
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
function toRad(deg: number): number {
return deg * (Math.PI / 180);
}
export function sortByDistance<T extends { lat: number; lng: number }>(items: T[], userLat: number, userLng: number): T[] {
return [...items].sort((a, b) => {
const distA = calculateDistance(userLat, userLng, a.lat, a.lng);
const distB = calculateDistance(userLat, userLng, b.lat, b.lng);
return distA - distB;
});
}
```
## Best Practices
1. **Lazy Loading**: Load map libraries only when needed to reduce initial bundle size
2. **Clustering**: Use marker clustering for maps with many points
3. **Caching**: Cache geocoding results to reduce API calls
4. **Permissions**: Handle geolocation permission denials gracefully
5. **Offline Support**: Consider offline map tiles for mobile applicationsThis maps prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their maps implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For maps projects, consider mentioning your framework version, coding style, and any specific libraries you're using.