Use Cases

Guia de uso de la API Geolocation con Claude Code

Aprenda sobre la API Geolocation usando Claude Code. Incluye consejos practicos y ejemplos de codigo.

Implementando funcionalidades basadas en ubicacion con la API Geolocation

Con la API Geolocation, puede obtener la ubicacion actual del usuario y ofrecer funcionalidades de busqueda local y navegacion. Aprovechando Claude Code, puede construir eficientemente implementaciones robustas que incluyen gestion de permisos y manejo de errores.

Obtencion basica de ubicacion

> Crea un hook de React para obtener la posicion actual del usuario.
> Incluye gestion de permisos, manejo de errores y estado de carga.
// hooks/useGeolocation.ts
import { useState, useEffect, useCallback } from 'react';

interface GeolocationState {
  latitude: number | null;
  longitude: number | null;
  accuracy: number | null;
  loading: boolean;
  error: string | null;
  timestamp: number | null;
}

interface UseGeolocationOptions {
  enableHighAccuracy?: boolean;
  timeout?: number;
  maximumAge?: number;
}

export function useGeolocation(options: UseGeolocationOptions = {}) {
  const [state, setState] = useState<GeolocationState>({
    latitude: null, longitude: null, accuracy: null,
    loading: false, error: null, timestamp: null,
  });

  const getCurrentPosition = useCallback(() => {
    if (!navigator.geolocation) {
      setState(prev => ({ ...prev, error: 'La API Geolocation no es compatible' }));
      return;
    }

    setState(prev => ({ ...prev, loading: true, error: null }));

    navigator.geolocation.getCurrentPosition(
      (position) => {
        setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          accuracy: position.coords.accuracy,
          loading: false, error: null,
          timestamp: position.timestamp,
        });
      },
      (error) => {
        const messages: Record<number, string> = {
          1: 'Se rechazo el acceso a la ubicacion',
          2: 'No se pudo obtener la ubicacion',
          3: 'La obtencion de ubicacion ha expirado',
        };
        setState(prev => ({
          ...prev, loading: false,
          error: messages[error.code] || 'Error desconocido',
        }));
      },
      {
        enableHighAccuracy: options.enableHighAccuracy ?? false,
        timeout: options.timeout ?? 10000,
        maximumAge: options.maximumAge ?? 0,
      }
    );
  }, [options.enableHighAccuracy, options.timeout, options.maximumAge]);

  return { ...state, getCurrentPosition };
}

Componente que utiliza ubicacion

// components/NearbySearch.tsx
import { useGeolocation } from '../hooks/useGeolocation';

export function NearbySearch() {
  const { latitude, longitude, loading, error, getCurrentPosition } = useGeolocation({
    enableHighAccuracy: true,
  });

  return (
    <div className="rounded-xl border p-6">
      <h2 className="mb-4 text-xl font-bold">Buscar lugares cercanos</h2>
      
      {!latitude && !loading && (
        <button
          onClick={getCurrentPosition}
          className="rounded-lg bg-blue-600 px-4 py-2 text-white hover:bg-blue-700"
        >
          Obtener ubicacion actual
        </button>
      )}

      {loading && (
        <div className="flex items-center gap-2 text-gray-600">
          Obteniendo ubicacion...
        </div>
      )}

      {error && (
        <div className="rounded-lg bg-red-50 p-3 text-red-600">{error}</div>
      )}

      {latitude && longitude && (
        <div>
          <p className="mb-2 text-sm text-gray-600">
            Ubicacion actual: {latitude.toFixed(4)}, {longitude.toFixed(4)}
          </p>
          <NearbyResults lat={latitude} lng={longitude} />
        </div>
      )}
    </div>
  );
}

Seguimiento de posicion en tiempo real

// hooks/useWatchPosition.ts
import { useState, useEffect, useRef } from 'react';

export function useWatchPosition() {
  const [positions, setPositions] = useState<GeolocationPosition[]>([]);
  const watchIdRef = useRef<number | null>(null);

  const startTracking = () => {
    if (!navigator.geolocation) return;

    watchIdRef.current = navigator.geolocation.watchPosition(
      (position) => {
        setPositions(prev => [...prev, position]);
      },
      (error) => console.error('Error de seguimiento:', error),
      { enableHighAccuracy: true, maximumAge: 5000 }
    );
  };

  const stopTracking = () => {
    if (watchIdRef.current !== null) {
      navigator.geolocation.clearWatch(watchIdRef.current);
      watchIdRef.current = null;
    }
  };

  useEffect(() => {
    return stopTracking;
  }, []);

  return { positions, startTracking, stopTracking };
}

Utilidad de calculo de distancia

// utils/geo.ts
export function haversineDistance(
  lat1: number, lon1: number,
  lat2: number, lon2: number
): number {
  const R = 6371; // Radio de la Tierra (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);
}

// Ejemplo de uso
const distance = haversineDistance(40.4168, -3.7038, 41.3851, 2.1734);
console.log(`Madrid a Barcelona: ${distance.toFixed(1)}km`); // Aprox. 504.6km

Consideraciones de privacidad

// Reducir intencionalmente la precision de la ubicacion (proteccion de privacidad)
function coarsenLocation(lat: number, lng: number, precision: number = 2) {
  return {
    latitude: Number(lat.toFixed(precision)),
    longitude: Number(lng.toFixed(precision)),
  };
}

// Difuminar antes de enviar al servidor
async function sendLocation(lat: number, lng: number) {
  const coarse = coarsenLocation(lat, lng);
  await fetch('/api/location', {
    method: 'POST',
    body: JSON.stringify(coarse),
  });
}

Resumen

La API Geolocation puede aprovecharse en muchos casos de uso como busqueda local y navegacion. Con Claude Code, puede construir eficientemente implementaciones que consideran seguridad y privacidad. Combine con diseno responsivo para optimizar la usabilidad en dispositivos moviles. Para las especificaciones detalladas de la API Geolocation, consulte MDN Web Docs.

#Claude Code #Geolocation #geolocalizacion #mapa #Web API