Debug School

rakesh kumar
rakesh kumar

Posted on

list out feature using google map in react

Live Location Tracking (User's Current Location)
Automatically fetch and display the user's current location on the map.

📝 Implementation

import React, { useState, useEffect } from "react";
import { GoogleMap, LoadScript, Marker } from "@react-google-maps/api";

const containerStyle = {
  width: "100%",
  height: "400px",
};

const LiveLocation = () => {
  const [currentLocation, setCurrentLocation] = useState(null);

  useEffect(() => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position) => {
        setCurrentLocation({
          lat: position.coords.latitude,
          lng: position.coords.longitude,
        });
      });
    }
  }, []);

  return (
    <LoadScript googleMapsApiKey="YOUR_GOOGLE_MAPS_API_KEY">
      <GoogleMap mapContainerStyle={containerStyle} center={currentLocation} zoom={15}>
        {currentLocation && <Marker position={currentLocation} />}
      </GoogleMap>
    </LoadScript>
  );
};

export default LiveLocation;
Enter fullscreen mode Exit fullscreen mode

2️⃣ Place Autocomplete (Search for Places)
Allows users to search for places using Google Places Autocomplete API.

📝 Implementation

import React, { useRef } from "react";
import { LoadScript } from "@react-google-maps/api";

const PlacesSearch = () => {
  const inputRef = useRef(null);

  const initAutocomplete = () => {
    const autocomplete = new window.google.maps.places.Autocomplete(inputRef.current);
    autocomplete.addListener("place_changed", () => {
      const place = autocomplete.getPlace();
      console.log("Selected Place:", place);
    });
  };

  return (
    <LoadScript googleMapsApiKey="YOUR_GOOGLE_MAPS_API_KEY" libraries={["places"]} onLoad={initAutocomplete}>
      <input type="text" ref={inputRef} placeholder="Search for places..." />
    </LoadScript>
  );
};

export default PlacesSearch;
Enter fullscreen mode Exit fullscreen mode

3️⃣ Distance & Duration Calculation (Google Directions API)
Calculate distance & estimated time between two locations.

📝 Implementation

import React, { useState } from "react";
import axios from "axios";

const DistanceCalculator = () => {
  const [distance, setDistance] = useState("");
  const [duration, setDuration] = useState("");

  const calculateDistance = async () => {
    const origin = "New York, USA";
    const destination = "Los Angeles, USA";
    const API_KEY = "YOUR_GOOGLE_MAPS_API_KEY";
    const url = `https://maps.googleapis.com/maps/api/directions/json?origin=${origin}&destination=${destination}&key=${API_KEY}`;

    const response = await axios.get(url);
    if (response.data.routes.length > 0) {
      const route = response.data.routes[0].legs[0];
      setDistance(route.distance.text);
      setDuration(route.duration.text);
    }
  };

  return (
    <div>
      <button onClick={calculateDistance}>Get Distance</button>
      <p>Distance: {distance}</p>
      <p>Duration: {duration}</p>
    </div>
  );
};

export default DistanceCalculator;
Enter fullscreen mode Exit fullscreen mode

4️⃣ Nearby Places (Find Restaurants, Hotels, etc.)
Find nearby places (e.g., restaurants, gas stations) using Google Places API.

import React, { useState } from "react";
import axios from "axios";

const NearbyPlaces = () => {
  const [places, setPlaces] = useState([]);

  const findNearbyRestaurants = async () => {
    const location = "37.7749,-122.4194"; // San Francisco, CA
    const API_KEY = "YOUR_GOOGLE_MAPS_API_KEY";
    const url = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${location}&radius=1500&type=restaurant&key=${API_KEY}`;

    const response = await axios.get(url);
    setPlaces(response.data.results);
  };

  return (
    <div>
      <button onClick={findNearbyRestaurants}>Find Nearby Restaurants</button>
      <ul>
        {places.map((place, index) => (
          <li key={index}>{place.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default NearbyPlaces;
Enter fullscreen mode Exit fullscreen mode

5️⃣ Traffic Layer (Real-time Traffic Information)
Display live traffic data on the map.

import React from "react";
import { GoogleMap, LoadScript, TrafficLayer } from "@react-google-maps/api";

const TrafficMap = () => (
  <LoadScript googleMapsApiKey="YOUR_GOOGLE_MAPS_API_KEY">
    <GoogleMap mapContainerStyle={{ width: "100%", height: "400px" }} center={{ lat: 37.7749, lng: -122.4194 }} zoom={12}>
      <TrafficLayer />
    </GoogleMap>
  </LoadScript>
);

export default TrafficMap;
Enter fullscreen mode Exit fullscreen mode

6️⃣ Street View (360° Panoramic View)
Allows users to view Google Street View.

📝 Implementation

import React from "react";
import { StreetViewPanorama, LoadScript } from "@react-google-maps/api";

const StreetViewMap = () => (
  <LoadScript googleMapsApiKey="YOUR_GOOGLE_MAPS_API_KEY">
    <StreetViewPanorama position={{ lat: 37.7749, lng: -122.4194 }} pov={{ heading: 100, pitch: 0 }} />
  </LoadScript>
);

export default StreetViewMap;
Enter fullscreen mode Exit fullscreen mode

7️⃣ Route Optimization (Waypoints)
Optimize routes by adding waypoints.

📝 Implementation

const url = `https://maps.googleapis.com/maps/api/directions/json?origin=San Francisco&destination=Los Angeles&waypoints=Sacramento|San Jose&key=YOUR_GOOGLE_MAPS_API_KEY`;
Enter fullscreen mode Exit fullscreen mode

8️⃣ Custom Map Styling (Dark Mode, Night Mode, etc.)
Use Google Maps Styling API for custom map themes.

📝 Implementation

const mapOptions = {
  styles: [
    {
      elementType: "geometry",
      stylers: [{ color: "#242f3e" }],
    },
    {
      elementType: "labels.text.stroke",
      stylers: [{ color: "#242f3e" }],
    },
    {
      elementType: "labels.text.fill",
      stylers: [{ color: "#746855" }],
    },
  ],
};
Enter fullscreen mode Exit fullscreen mode

9️⃣ Heatmaps (Data Visualization)
Use Google Maps Heatmap Layer to visualize high-density data.

🔟 Geofencing (Restrict Areas)
Block users from selecting or accessing restricted zones.

📝 Implementation

const restrictedArea = new google.maps.Circle({
  center: { lat: 37.7749, lng: -122.4194 },
  radius: 5000,
  strokeColor: "#FF0000",
  strokeOpacity: 0.8,
  fillColor: "#FF0000",
  fillOpacity: 0.35,
});
Enter fullscreen mode Exit fullscreen mode

Heatmaps for Popular Locations
Visualize user engagement and customer traffic on the map.

📝 Implementation

import { GoogleMap, LoadScript, HeatmapLayer } from "@react-google-maps/api";

const heatmapData = [
  new window.google.maps.LatLng(37.7749, -122.4194),
  new window.google.maps.LatLng(37.7849, -122.4294),
];

const HeatmapExample = () => (
  <LoadScript googleMapsApiKey="YOUR_GOOGLE_MAPS_API_KEY">
    <GoogleMap mapContainerStyle={{ width: "100%", height: "400px" }} center={{ lat: 37.7749, lng: -122.4194 }} zoom={12}>
      <HeatmapLayer data={heatmapData} />
    </GoogleMap>
  </LoadScript>
);

export default HeatmapExample;
Enter fullscreen mode Exit fullscreen mode

Practical implemention of google maps

step1:Run dependency

npm install @react-google-maps/api @fullcalendar/react @fullcalendar/daygrid @fullcalendar/timegrid @fullcalendar/interaction

===============OR======================================

npm install @react-google-maps/api
Enter fullscreen mode Exit fullscreen mode

step2:import calender dependencey

import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import "./Calendar.css";
import GoogleMapSelector from "./GoogleMapSelector"; // Import the new map component
Enter fullscreen mode Exit fullscreen mode
.google-map-container {
    width: 100%;
    max-width: 600px;
    height: 400px;
    margin: 20px auto;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
}
Enter fullscreen mode Exit fullscreen mode

step3: declare variable

 const [selectedLocation, setSelectedLocation] = useState({
    latitude: vehicle?.latitude || 12.9716, // Default to some location (e.g., Bangalore)
    longitude: vehicle?.longitude || 77.5946,
  });
Enter fullscreen mode Exit fullscreen mode

step4:change format

 const safeLatitude = Number(vehicle?.latitude) || 12.9716;
  const safeLongitude = Number(vehicle?.longitude) || 77.5946;
Enter fullscreen mode Exit fullscreen mode

step5:Set component

 <div className="location-container">
          <h5>Select Location on Map</h5>
          <GoogleMapSelector
    defaultLocation={{
        lat: selectedLocation.latitude ?? safeLatitude,
        lng: selectedLocation.longitude ?? safeLongitude
    }}
    onLocationSelect={handleLocationSelect}
/>

        </div>
Enter fullscreen mode Exit fullscreen mode

step6:Define methods

  const handleLocationSelect = (newLocation) => {
    setSelectedLocation(newLocation);
  };
Enter fullscreen mode Exit fullscreen mode

New jsx file

import React, { useState, useEffect } from "react";
import { GoogleMap, LoadScript, Marker, InfoWindow } from "@react-google-maps/api";
import axios from "axios"; // Import Axios for API calls

const containerStyle = {
  width: "100%",
  height: "400px",
  borderRadius: "10px",
};

const GoogleMapSelector = ({ defaultLocation, onLocationSelect }) => {
  const [markerPosition, setMarkerPosition] = useState({
    lat: Number(defaultLocation.lat) || 12.9716,
    lng: Number(defaultLocation.lng) || 77.5946,
  });
  const [address, setAddress] = useState("Fetching address..."); // Store address
  const [infoOpen, setInfoOpen] = useState(true); // Control InfoWindow visibility

  useEffect(() => {
    if (defaultLocation?.lat && defaultLocation?.lng) {
      setMarkerPosition({
        lat: Number(defaultLocation.lat) || 12.9716,
        lng: Number(defaultLocation.lng) || 77.5946,
      });
      fetchAddress(Number(defaultLocation.lat), Number(defaultLocation.lng)); // Fetch initial address
    }
  }, [defaultLocation]);

  // Function to fetch address using Google Geocoding API
  const fetchAddress = async (lat, lng) => {
    const API_KEY = "AIzaSyBhaPrPa87NhhvxYRxe1CwsCMaAZBBE-sw"; // Replace with your API Key
    const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${API_KEY}`;

    try {
      const response = await axios.get(url);
      if (response.data.results.length > 0) {
        setAddress(response.data.results[0].formatted_address);
      } else {
        setAddress("Address not found");
      }
    } catch (error) {
      console.error("Error fetching address:", error);
      setAddress("Failed to load address");
    }
  };

  // Function to update location on map click
  const onMapClick = (event) => {
    const newLat = event.latLng?.lat();
    const newLng = event.latLng?.lng();

    if (!newLat || !newLng || isNaN(newLat) || isNaN(newLng)) return;

    setMarkerPosition({ lat: newLat, lng: newLng });
    onLocationSelect({ latitude: newLat, longitude: newLng });
    fetchAddress(newLat, newLng); // Fetch new address
    setInfoOpen(true); // Open InfoWindow
  };

  // Function to update location when marker is dragged
  const onMarkerDragEnd = (event) => {
    const newLat = event.latLng?.lat();
    const newLng = event.latLng?.lng();

    if (!newLat || !newLng || isNaN(newLat) || isNaN(newLng)) return;

    setMarkerPosition({ lat: newLat, lng: newLng });
    onLocationSelect({ latitude: newLat, longitude: newLng });
    fetchAddress(newLat, newLng); // Fetch new address
    setInfoOpen(true); // Open InfoWindow
  };

  return (
    <LoadScript googleMapsApiKey="AIzaSyBhaPrPa87NhhvxYRxe1CwsCMaAZBBE-sw">
      <GoogleMap
        mapContainerStyle={containerStyle}
        center={markerPosition}
        zoom={15}
        onClick={onMapClick} // Update position on map click
      >
        {markerPosition.lat && markerPosition.lng && (
          <Marker
            position={markerPosition}
            draggable={true} // Enable dragging
            onDragEnd={onMarkerDragEnd} // Update position when dragged
            onClick={() => setInfoOpen(true)} // Open InfoWindow when clicked
          >
            {/* Show InfoWindow on Marker */}
            {infoOpen && (
              <InfoWindow
                position={markerPosition}
                onCloseClick={() => setInfoOpen(false)}
              >
                <div style={{ padding: "-2px", fontSize: "12px" }}>

                <h5>Motoshare</h5>

                  <strong>📍 Shop Location</strong>
                  <p>{address}</p>
                </div>
              </InfoWindow>
            )}
          </Marker>
        )}
      </GoogleMap>
    </LoadScript>
  );
};

export default GoogleMapSelector;
Enter fullscreen mode Exit fullscreen mode

Full Code

import React, { useState, useEffect } from "react";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import axios from "axios"; // Axios for API calls
import SearchvehicleFilter from "./SearchvehicleFilter";
import ImageSlider from "./ImageSlider";
import "./Calendar.css";
import SelectableMap from "./SelectableMap"; // Import the new map component
import GoogleMapSelector from "./GoogleMapSelector"; // Import the new map componen

const VehicleDetails = ({ vehicle, location, bookings = [] }) => {


  const [popupVisible, setPopupVisible] = useState(false);
  const [filteredVehicles, setFilteredVehicles] = useState([]);
  const [selectedRange, setSelectedRange] = useState(null);
  const [calendarEvents, setCalendarEvents] = useState([]);
  const [selectedLocation, setSelectedLocation] = useState({
    latitude: vehicle?.latitude || 12.9716, // Default to some location (e.g., Bangalore)
    longitude: vehicle?.longitude || 77.5946,
  });
  const safeLatitude = Number(vehicle?.latitude) || 12.9716;
  const safeLongitude = Number(vehicle?.longitude) || 77.5946;
  const handlePopupOpen = () => setPopupVisible(true);

  const handlePopupClose = () => setPopupVisible(false);

  const handleSearch = (term) => {
    const results = location.filter((loc) =>
      loc.city.toLowerCase().includes(term.toLowerCase())
    );
    setFilteredVehicles(results);
  };

  const handleLocationSelect = (newLocation) => {
    setSelectedLocation(newLocation);
  };

  const handleDateSelect = (selectInfo) => {
    selectInfo.jsEvent.preventDefault(); // Prevents default browser behavior

    const { startStr, endStr } = selectInfo;

    // Correct end date for display and backend (subtract one day)
    const correctedEndDate = new Date(endStr);
    correctedEndDate.setDate(correctedEndDate.getDate() - 1);
    const formattedEndDate = correctedEndDate.toISOString().split("T")[0];

    // Set the selected range (corrected for UI and backend)
    setSelectedRange({
        start: startStr,
        end: formattedEndDate, // Corrected for proper display
    });

    // Add event to FullCalendar (WITHOUT subtracting one day)
    setCalendarEvents((prevEvents) => [
        ...prevEvents,
        {
            start: startStr,
            end: endStr, // Keep FullCalendar's behavior (no correction)
            backgroundColor: "purple",
            borderColor: "purple",
            display: "background",
        },
    ]);

    setPopupVisible(true);
};

  const handleFilter = (filter) => {
    if (filter) {
      const results = location.filter((loc) => loc.vehicleType === filter);
      setFilteredVehicles(results);
    } else {
      setFilteredVehicles(location);
    }
  };

  const handleRentNow = async () => {
    try {
        // Prepare request payload
        const payload = {
            vehicle_id: vehicle?.id, // Vehicle ID
        };

        // Only include start_date and end_date if they are selected
        if (selectedRange?.start && selectedRange?.end) {
            payload.start_date = selectedRange.start;
            payload.end_date = selectedRange.end;
        }

        const response = await axios.post(
            `/rent-vehicle`, // Replace with your backend route
            payload,
            {
                headers: {
                    "Content-Type": "application/json",
                },
            }
        );

        if (response.data.success) {       
            // Redirect user to the dynamic booking page
            window.location.href = response.data.redirect_url; 
        } else {
            alert(response.data.message || "Failed to rent vehicle.");
        }
    } catch (error) {
        console.error("Rent Now Error:", error);
        alert("An error occurred while renting the vehicle. Please try again.");
    }
};


  useEffect(() => {
    if (Array.isArray(bookings)) {
      const bookedDates = bookings.map((booking) => ({
        start: booking.start_date,
        end: booking.end_date,
        backgroundColor: "#ff9999",
        borderColor: "#ff6666",
        display: "background",
      }));
      setCalendarEvents(bookedDates);
    }
  }, [bookings]);

  const vehicleImages = Array.isArray(vehicle?.vechicle_image)
    ? vehicle?.vechicle_image
    : JSON.parse(vehicle?.vechicle_image || "[]");

  return (
    <div className="vehicle-details-container">
      <SearchvehicleFilter onSearch={handleSearch} onFilter={handleFilter} />

      <div className="vehicle-content-wrapper">
        <div className="vehicle-image-container">
          <ImageSlider imageUrls={vehicleImages} />
          <div className="vehicle-info">
            <span className="kms-driven">🚗 {vehicle?.kms_driven || "0"} kms driven</span>
            <span className="make-year">📅 {vehicle?.make_year || "Unknown Year"}</span>
          </div>
        </div>

        <div className="vehicle-details">
          <div className="vehicle-details-box">
            <h3>Vehicle Details</h3>
            <p><strong>Vehicle:</strong> {vehicle?.vechicle || "N/A"}</p>
            <p><strong>Brand:</strong> {vehicle?.brand || "Unknown Brand"}</p>
            <p><strong>Model:</strong> {vehicle?.model || "N/A"}</p>
            <p><strong>City:</strong> {vehicle?.city || "N/A"}</p>
            <p><strong>Shop Location:</strong> {vehicle?.shoplocation || "N/A"}</p>
            <p><strong>Price:</strong> <strong>{vehicle?.price || "N/A"} INR</strong></p>
          </div>
          <button className="book-now-button" onClick={handleRentNow}>Rent Now</button>
        </div>
      </div>

      <div className="location-calendar-section">
      <div className="location-container">
          <h5>Select Location on Map</h5>
          <GoogleMapSelector
    defaultLocation={{
        lat: selectedLocation.latitude ?? safeLatitude,
        lng: selectedLocation.longitude ?? safeLongitude
    }}
    onLocationSelect={handleLocationSelect}
/>

        </div>

        <div className="calendar-container">
          <div className="calendar-header">
            <div className="calendar-title">

            </div>
            <div className="calendar-legend">
              <div className="legend-item">
                <span className="legend-color available"></span> Available
              </div>
              <div className="legend-item">
                <span className="legend-color booked"></span> Booked
              </div>
            </div>
          </div>

          <div className="small-calendar" id="calendar1">
            <h5>Availibility</h5>
            {selectedRange && (
  <p style={{ backgroundColor: 'yellow', padding: '10px', borderRadius: '5px', marginBottom: '10px' }}>
    Selected Range: {selectedRange.start} to {new Date(selectedRange.end).toISOString().split("T")[0]}
  </p>
)}
            <FullCalendar
              plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
              initialView="dayGridMonth"
              selectable={true}
              selectMirror={true}
              events={calendarEvents}
              select={handleDateSelect}
              headerToolbar={{
                left: "prev,next",
                center: "title",
                right: "dayGridMonth,timeGridWeek,timeGridDay",
              }}
              height="auto"
              contentHeight="auto"
              aspectRatio={1.2}
              fixedWeekCount={false}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default VehicleDetails;
Enter fullscreen mode Exit fullscreen mode

10 Unique AI & Machine Learning Features Using Google Maps in React

Predictive Heatmaps (AI-Driven User Traffic Patterns)
Using historical data & AI, predict future customer movement patterns on Google Maps.

📝 Implementation (Using TensorFlow.js for Predictions)

import { GoogleMap, LoadScript, HeatmapLayer } from "@react-google-maps/api";
import * as tf from "@tensorflow/tfjs";

const historicalData = [
  { lat: 37.7749, lng: -122.4194, density: 100 },
  { lat: 37.7849, lng: -122.4294, density: 50 },
];

// AI-Powered Heatmap Prediction
const predictHeatmap = async () => {
  const model = tf.sequential();
  model.add(tf.layers.dense({ units: 1, inputShape: [2] }));
  model.compile({ loss: "meanSquaredError", optimizer: "sgd" });

  const inputs = tf.tensor2d(historicalData.map(d => [d.lat, d.lng]));
  const outputs = tf.tensor2d(historicalData.map(d => [d.density]));

  await model.fit(inputs, outputs, { epochs: 10 });

  const predictions = model.predict(tf.tensor2d([[37.7909, -122.4100]]));
  return predictions.dataSync();
};

const AIHeatmap = async () => {
  const predictedDensity = await predictHeatmap();
  return [
    new window.google.maps.LatLng(37.7909, -122.4100, predictedDensity[0])
  ];
};

const HeatmapExample = () => (
  <LoadScript googleMapsApiKey="YOUR_GOOGLE_MAPS_API_KEY">
    <GoogleMap mapContainerStyle={{ width: "100%", height: "400px" }} center={{ lat: 37.7749, lng: -122.4194 }} zoom={12}>
      <HeatmapLayer data={AIHeatmap()} />
    </GoogleMap>
  </LoadScript>
);

export default HeatmapExample;
Enter fullscreen mode Exit fullscreen mode

📌 Use Case: Predict customer density in shopping malls, tourist locations, event venues.

2️⃣ AI-Based Route Optimization (Shortest Path with Traffic Prediction)
Use machine learning models to optimize delivery routes dynamically based on traffic, weather, and road conditions.

📝 Implementation (Google Directions API + AI)

import axios from "axios";

const getOptimizedRoute = async (origin, destination) => {
  const response = await axios.get(
    `https://maps.googleapis.com/maps/api/directions/json?origin=${origin}&destination=${destination}&key=YOUR_GOOGLE_MAPS_API_KEY`
  );

  // AI can refine routes based on real-time data
  const bestRoute = response.data.routes[0]; 
  console.log("Optimized Route:", bestRoute);
};

getOptimizedRoute("San Francisco, CA", "Los Angeles, CA");
Enter fullscreen mode Exit fullscreen mode

📌 Use Case: AI-based route optimization for delivery apps, ride-sharing services, logistics.

3️⃣ Real-Time Anomaly Detection (Detect Abnormal Events on the Map)
Use AI to detect traffic jams, accidents, or unusual crowd movements.

📝 Implementation (Using TensorFlow.js for Outlier Detection)

import * as tf from "@tensorflow/tfjs";

const detectAnomalies = async (dataPoints) => {
  const model = tf.sequential();
  model.add(tf.layers.dense({ units: 1, inputShape: [2] }));
  model.compile({ loss: "meanSquaredError", optimizer: "sgd" });

  const inputs = tf.tensor2d(dataPoints.map(d => [d.lat, d.lng]));
  const outputs = tf.tensor2d(dataPoints.map(d => [d.activityLevel]));

  await model.fit(inputs, outputs, { epochs: 10 });

  const anomalies = dataPoints.filter(d => d.activityLevel > 100);
  return anomalies;
};

const eventData = [
  { lat: 37.7749, lng: -122.4194, activityLevel: 20 },
  { lat: 37.7849, lng: -122.4294, activityLevel: 200 }, // Anomaly
];

detectAnomalies(eventData).then(anomalies => console.log("Detected anomalies:", anomalies));
Enter fullscreen mode Exit fullscreen mode

📌 Use Case: Detect unusual traffic, suspicious activity in public places, crime monitoring.

4️⃣ AI-Based Geofencing for Smart Notifications
Trigger custom AI-driven notifications based on user location.

📝 Implementation

const userLocation = { lat: 37.7749, lng: -122.4194 };
const restrictedArea = { lat: 37.7800, lng: -122.4200, radius: 100 };

const isInsideGeofence = (user, area) => {
  const distance = Math.sqrt((user.lat - area.lat) ** 2 + (user.lng - area.lng) ** 2);
  return distance < area.radius;
};

if (isInsideGeofence(userLocation, restrictedArea)) {
  console.log("🚨 Warning! You have entered a restricted zone.");
}
Enter fullscreen mode Exit fullscreen mode

📌 Use Case: Smart parking alerts, security notifications, personalized marketing alerts.

5️⃣ AI-Powered Location-Based Recommendations
Recommend places based on user behavior.

📝 Implementation (Google Places API + AI)

import axios from "axios";

const getNearbyRecommendations = async (userLocation) => {
  const response = await axios.get(
    `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${userLocation.lat},${userLocation.lng}&radius=1000&type=restaurant&key=YOUR_GOOGLE_MAPS_API_KEY`
  );

  console.log("Recommended Places:", response.data.results);
};

getNearbyRecommendations({ lat: 37.7749, lng: -122.4194 });
Enter fullscreen mode Exit fullscreen mode

AI-Powered Parking Availability Detection 🚗
📝 Description
Uses Google Street View & AI image processing to detect empty parking spots.

import axios from "axios";
import * as tf from "@tensorflow/tfjs";

const GOOGLE_VISION_API_KEY = "YOUR_GOOGLE_VISION_API_KEY";
const PARKING_MODEL_URL = "/models/parking-spot-detector/model.json"; // Pre-trained AI model

const detectParkingSpots = async (imageUrl) => {
  // Load AI Model
  const model = await tf.loadLayersModel(PARKING_MODEL_URL);

  // Google Vision API to Analyze Image
  const response = await axios.post(
    `https://vision.googleapis.com/v1/images:annotate?key=${GOOGLE_VISION_API_KEY}`,
    {
      requests: [
        {
          image: { source: { imageUri: imageUrl } },
          features: [{ type: "LABEL_DETECTION" }],
        },
      ],
    }
  );

  // Analyze Image Labels
  const labels = response.data.responses[0].labelAnnotations;
  const isParkingAvailable = labels.some((label) => label.description === "parking lot" && label.score > 0.7);

  console.log(isParkingAvailable ? "✅ Parking Spot Available!" : "🚫 No Parking Spot Found!");
};

detectParkingSpots("https://example.com/street-view-image.jpg");
Enter fullscreen mode Exit fullscreen mode

📌 Use Case: Smart city parking apps, valet services, AI parking sensors.

2️⃣ AI-Based Crime Mapping & Risk Prediction 🚔
📝 Description
Uses crime data + AI to predict dangerous areas and map crime hotspots.

🔹 Implementation (Using Crime API & AI Predictions)

import axios from "axios";
import { GoogleMap, LoadScript, Marker } from "@react-google-maps/api";
import * as tf from "@tensorflow/tfjs";

const CRIME_API_URL = "https://api.crimeometer.com/v1/incidents/raw-data";
const CRIME_MODEL_URL = "/models/crime-prediction/model.json"; // AI model for crime risk

const fetchCrimeData = async (lat, lng) => {
  const response = await axios.get(`${CRIME_API_URL}?lat=${lat}&lng=${lng}&radius=5km`);
  return response.data.incidents;
};

const predictCrimeRisk = async (crimeData) => {
  const model = await tf.loadLayersModel(CRIME_MODEL_URL);
  const inputs = tf.tensor2d(crimeData.map((crime) => [crime.latitude, crime.longitude, crime.crime_type]));
  const predictions = model.predict(inputs);
  return predictions.dataSync();
};

const CrimeMap = () => {
  const [crimeSpots, setCrimeSpots] = useState([]);

  useEffect(() => {
    fetchCrimeData(37.7749, -122.4194).then(async (crimeData) => {
      const predictions = await predictCrimeRisk(crimeData);
      setCrimeSpots(predictions);
    });
  }, []);

  return (
    <LoadScript googleMapsApiKey="YOUR_GOOGLE_MAPS_API_KEY">
      <GoogleMap center={{ lat: 37.7749, lng: -122.4194 }} zoom={12} mapContainerStyle={{ width: "100%", height: "500px" }}>
        {crimeSpots.map((spot, index) => (
          <Marker key={index} position={{ lat: spot.lat, lng: spot.lng }} label="🚔" />
        ))}
      </GoogleMap>
    </LoadScript>
  );
};

export default CrimeMap;
Enter fullscreen mode Exit fullscreen mode

📌 Use Case: Predict crime-prone areas for public safety, smart policing, emergency alerts.

3️⃣ AI-Based Demand Prediction for Ridesharing & Delivery 🚖
📝 Description
Uses historical ride request data + AI to predict surge pricing and ride demand.

🔹 Implementation (Using TensorFlow.js)

import * as tf from "@tensorflow/tfjs";

const rideData = [
  { hour: 8, demand: 200 },
  { hour: 12, demand: 150 },
  { hour: 18, demand: 300 },
];

const predictDemand = async (hour) => {
  const model = tf.sequential();
  model.add(tf.layers.dense({ units: 1, inputShape: [1] }));
  model.compile({ loss: "meanSquaredError", optimizer: "sgd" });

  const inputs = tf.tensor2d(rideData.map((d) => [d.hour]));
  const outputs = tf.tensor2d(rideData.map((d) => [d.demand]));

  await model.fit(inputs, outputs, { epochs: 10 });

  const predictions = model.predict(tf.tensor2d([[hour]]));
  return predictions.dataSync();
};

predictDemand(17).then((demand) => console.log("Predicted Ride Demand:", demand));
Enter fullscreen mode Exit fullscreen mode

📌 Use Case: Dynamic pricing for ride-sharing apps (Uber, Lyft), delivery route optimization.

4️⃣ AI-Driven Environmental Monitoring (Air Quality & Pollution Mapping) 🌎
📝 Description
Uses air pollution APIs + AI to predict air quality in real-time.

🔹 Implementation (Using AQICN API + AI Models)

import axios from "axios";
import * as tf from "@tensorflow/tfjs";

const AIR_QUALITY_API_URL = "https://api.waqi.info/feed/geo:37.7749;-122.4194/?token=YOUR_AQI_API_KEY";

const fetchAirQuality = async () => {
  const response = await axios.get(AIR_QUALITY_API_URL);
  return response.data.data.aqi;
};

const predictAirQuality = async (historicalData) => {
  const model = tf.sequential();
  model.add(tf.layers.dense({ units: 1, inputShape: [1] }));
  model.compile({ loss: "meanSquaredError", optimizer: "sgd" });

  const inputs = tf.tensor2d(historicalData.map((d) => [d.day]));
  const outputs = tf.tensor2d(historicalData.map((d) => [d.aqi]));

  await model.fit(inputs, outputs, { epochs: 10 });

  const predictions = model.predict(tf.tensor2d([[30]]));
  return predictions.dataSync();
};

fetchAirQuality().then((aqi) => console.log("Current AQI:", aqi));
Enter fullscreen mode Exit fullscreen mode

📌 Use Case: Real-time air pollution tracking, smart city environmental monitoring.

5️⃣ AI-Based Disaster Response & Risk Mapping 🌪️
📝 Description
Uses satellite data + AI to predict disasters like floods, earthquakes, wildfires.

🔹 Implementation (Using NASA API + AI)

import axios from "axios";
import * as tf from "@tensorflow/tfjs";

const NASA_DISASTER_API = "https://eonet.gsfc.nasa.gov/api/v2.1/events";

const fetchDisasters = async () => {
  const response = await axios.get(NASA_DISASTER_API);
  return response.data.events.map((event) => ({
    title: event.title,
    lat: event.geometries[0].coordinates[1],
    lng: event.geometries[0].coordinates[0],
  }));
};

const predictDisasters = async (data) => {
  const model = tf.sequential();
  model.add(tf.layers.dense({ units: 1, inputShape: [1] }));
  model.compile({ loss: "meanSquaredError", optimizer: "sgd" });

  const inputs = tf.tensor2d(data.map((d) => [d.year]));
  const outputs = tf.tensor2d(data.map((d) => [d.intensity]));

  await model.fit(inputs, outputs, { epochs: 10 });

  const predictions = model.predict(tf.tensor2d([[2025]]));
  return predictions.dataSync();
};

fetchDisasters().then((disasters) => console.log("Active Disasters:", disasters));
Enter fullscreen mode Exit fullscreen mode
Parking Spot Detection
✅ Crime Prediction
✅ Ridesharing Demand Prediction
✅ Air Quality Monitoring
✅ Disaster Risk Mapping
Enter fullscreen mode Exit fullscreen mode

Top comments (0)