Skip to main content

3 posts tagged with "gis"

View All Tags

Deep Dive into Google Maps Overlay Types with React + TypeScript

· 8 min read
  1. Introduction to Google Maps Overlays
  2. Markers
  3. Polygons
  4. Polylines
  5. Circles
  6. Rectangles
  7. InfoWindows
  8. GroundOverlay
  9. Custom Overlays
  10. Conclusion

Introduction to Google Maps Overlays​

Overlays are graphical elements that you can add to a Google Map to represent data or highlight specific areas. Google Maps supports the following overlay types:

  • Markers: Represent points of interest.
  • Polygons: Represent closed shapes with multiple vertices.
  • Polylines: Represent lines with multiple vertices.
  • Circles: Represent circular areas.
  • Rectangles: Represent rectangular areas.
  • InfoWindows: Display information about a specific location when a marker is clicked.
  • GroundOverlay: Displays an image or a video over a defined geographical area.
  • Custom Overlays: Allows developers to create their own custom overlays using HTML elements and JavaScript.

Markers​

Markers are used to represent points of interest on the map. Google Maps provides two types of markers:

  • Basic Marker: The traditional marker with a default icon.
  • AdvancedMarkerElement: A customizable marker with support for custom icons and content.

Basic Marker​

Here’s how to create a basic marker:

import React, { useEffect, useRef } from "react";

const BasicMarker: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Add a basic marker
new google.maps.Marker({
position: { lat: 37.7749, lng: -122.4194 },
map: mapRef.current,
title: "San Francisco",
});
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default BasicMarker;

Custom Marker with AdvancedMarkerElement​

The AdvancedMarkerElement allows you to create highly customizable markers. Here’s an example:

import React, { useEffect, useRef } from "react";

const CustomMarker: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Create a custom marker
const pinElement = document.createElement("div");
pinElement.innerHTML = "📍"; // Custom icon
pinElement.style.fontSize = "24px";

new google.maps.marker.AdvancedMarkerElement({
position: { lat: 37.7749, lng: -122.4194 },
map: mapRef.current,
content: pinElement,
});
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default CustomMarker;

Polygons​

Polygons are used to represent closed shapes with multiple vertices. You can customize their appearance and handle user interactions.

Drawing a Polygon​

Here’s how to draw a polygon:

import React, { useEffect, useRef } from "react";

const PolygonOverlay: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Define the polygon's path
const polygonCoords = [
{ lat: 37.7749, lng: -122.4194 },
{ lat: 37.7849, lng: -122.4294 },
{ lat: 37.7949, lng: -122.4094 },
];

// Draw the polygon
new google.maps.Polygon({
paths: polygonCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: mapRef.current,
});
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default PolygonOverlay;

Handling Polygon Events​

You can handle events like click, mouseover, and mouseout on polygons:

const polygon = new google.maps.Polygon({
paths: polygonCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: mapRef.current,
});

polygon.addListener("click", (event: google.maps.PolyMouseEvent) => {
console.log("Polygon clicked at:", event.latLng);
});

Polylines​

Polylines are used to represent lines with multiple vertices. They are useful for drawing routes or paths.

Drawing a Polyline​

Here’s how to draw a polyline:

import React, { useEffect, useRef } from "react";

const PolylineOverlay: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Define the polyline's path
const polylineCoords = [
{ lat: 37.7749, lng: -122.4194 },
{ lat: 37.7849, lng: -122.4294 },
{ lat: 37.7949, lng: -122.4094 },
];

// Draw the polyline
new google.maps.Polyline({
path: polylineCoords,
strokeColor: "#0000FF",
strokeOpacity: 1.0,
strokeWeight: 4,
map: mapRef.current,
});
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default PolylineOverlay;

Handling Polyline Events​

You can handle events like click on polylines:

const polyline = new google.maps.Polyline({
path: polylineCoords,
strokeColor: "#0000FF",
strokeOpacity: 1.0,
strokeWeight: 4,
map: mapRef.current,
});

polyline.addListener("click", (event: google.maps.PolyMouseEvent) => {
console.log("Polyline clicked at:", event.latLng);
});

Circles​

Circles are used to represent circular areas on the map. You can customize their radius, color, and opacity.

Drawing a Circle​

Here’s how to draw a circle:

import React, { useEffect, useRef } from "react";

const CircleOverlay: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Draw the circle
new google.maps.Circle({
center: { lat: 37.7749, lng: -122.4194 },
radius: 1000, // Radius in meters
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: mapRef.current,
});
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default CircleOverlay;

Handling Circle Events​

You can handle events like click on circles:

const circle = new google.maps.Circle({
center: { lat: 37.7749, lng: -122.4194 },
radius: 1000,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: mapRef.current,
});

circle.addListener("click", (event: google.maps.MapMouseEvent) => {
console.log("Circle clicked at:", event.latLng);
});

Rectangles​

Rectangles are used to represent rectangular areas on the map. You can customize their bounds, color, and opacity.

Drawing a Rectangle​

Here’s how to draw a rectangle:

import React, { useEffect, useRef } from "react";

const RectangleOverlay: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Define the rectangle's bounds
const rectangleBounds = {
north: 37.7849,
south: 37.7649,
east: -122.4094,
west: -122.4294,
};

// Draw the rectangle
new google.maps.Rectangle({
bounds: rectangleBounds,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.35,
map: mapRef.current,
});
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default RectangleOverlay;

Handling Rectangle Events​

You can handle events like click on rectangles:

const rectangle = new google.maps.Rectangle({
bounds: rectangleBounds,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.35,
map: mapRef.current,
});

rectangle.addListener("click", (event: google.maps.MapMouseEvent) => {
console.log("Rectangle clicked at:", event.latLng);
});

InfoWindows​

InfoWindows are used to display additional information about a location on the map. They are typically attached to markers but can also be used independently.

Adding an InfoWindow​

Here’s how to add an InfoWindow to a marker:

import React, { useEffect, useRef } from "react";

const InfoWindowExample: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Create a marker
const marker = new google.maps.Marker({
position: { lat: 37.7749, lng: -122.4194 },
map: mapRef.current,
title: "San Francisco",
});

// Create an InfoWindow
const infoWindow = new google.maps.InfoWindow({
content: "<h3>San Francisco</h3><p>Welcome to the Golden City!</p>",
});

// Attach the InfoWindow to the marker
marker.addListener("click", () => {
infoWindow.open(mapRef.current, marker);
});
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default InfoWindowExample;

Handling InfoWindow Events​

You can handle events like closeclick on InfoWindows:

infoWindow.addListener("closeclick", () => {
console.log("InfoWindow closed");
});

GroundOverlay​

GroundOverlays are used to overlay images (e.g., maps, satellite imagery) on specific areas of the map.

Adding a GroundOverlay​

Here’s how to add a GroundOverlay:

import React, { useEffect, useRef } from "react";

const GroundOverlayExample: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Define the bounds for the GroundOverlay
const bounds = {
north: 37.7849,
south: 37.7649,
east: -122.4094,
west: -122.4294,
};

// Add a GroundOverlay
new google.maps.GroundOverlay(
"https://www.example.com/image.png", // URL of the image
bounds,
{
map: mapRef.current,
opacity: 0.5, // Set the opacity of the overlay
}
);
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default GroundOverlayExample;

Custom Overlays​

Custom Overlays allow you to create fully custom overlays using HTML, CSS, and JavaScript. This is useful for adding complex UI elements to the map.

Creating a Custom Overlay​

Here’s how to create a custom overlay:

import React, { useEffect, useRef } from "react";

class CustomOverlay extends google.maps.OverlayView {
private div: HTMLElement | null = null;

constructor(
private position: google.maps.LatLng,
private content: string
) {
super();
}

onAdd(): void {
this.div = document.createElement("div");
this.div.style.position = "absolute";
this.div.style.backgroundColor = "white";
this.div.style.border = "1px solid black";
this.div.style.padding = "10px";
this.div.innerHTML = this.content;

const panes = this.getPanes();
if (panes) {
panes.overlayLayer.appendChild(this.div);
}
}

draw(): void {
if (this.div) {
const projection = this.getProjection();
const point = projection.fromLatLngToDivPixel(this.position);

if (point) {
this.div.style.left = `${point.x}px`;
this.div.style.top = `${point.y}px`;
}
}
}

onRemove(): void {
if (this.div) {
this.div.parentNode?.removeChild(this.div);
this.div = null;
}
}
}

const CustomOverlayExample: React.FC = () => {
const mapRef = useRef<google.maps.Map | null>(null);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
});

// Create a custom overlay
const overlay = new CustomOverlay(
new google.maps.LatLng(37.7749, -122.4194),
"<h3>Custom Overlay</h3><p>This is a custom overlay!</p>"
);

// Add the overlay to the map
overlay.setMap(mapRef.current);
}
}, []);

return <div id="map" style={{ height: "100vh", width: "100%" }} />;
};

export default CustomOverlayExample;

References:​

Setting Up Google Maps in React​

Before diving into overlays, ensure you have set up the Google Maps JavaScript API in your React application. Follow the steps in the Google Maps Documentation to obtain your API key and include it in your project.

Deep Dive Developing a React TypeScript Application for Google Maps

· 4 min read

Choosing the Right React Library for Google Maps​

There are two popular libraries for integrating Google Maps into React applications:

1. react-google-maps-api​

Features:​

  • Built with TypeScript support out of the box.
  • Highly optimized for performance.
  • Provides detailed type definitions for Google Maps API objects and events.
  • Supports SSR (Server-Side Rendering) and lazy loading of the Google Maps API.

Pros:​

  • Excellent TypeScript support.
  • Well-maintained and frequently updated.
  • Extensive documentation and examples.

Cons:​

  • Requires a steeper learning curve due to its focus on optimization and customization.

2. @react-google-maps/api​

Features:​

  • A modern, lightweight alternative to react-google-maps-api.
  • Provides a simple and intuitive API for Google Maps integration.
  • Supports TypeScript.
  • Optimized for performance with lazy loading and minimal re-renders.

Pros:​

  • Lightweight and fast.
  • Easy to use with minimal boilerplate.
  • Excellent TypeScript support.

Cons:​

  • Less mature compared to react-google-maps-api.
  • Fewer community resources and examples.

Recommendation:​

For most applications, react-google-maps-api is the preferred choice due to its robust TypeScript support and active development. However, for simpler projects, @react-google-maps/api may be sufficient.


Key Considerations for Google Maps Event Handling​

1. Event Compatibility​

Google Maps provides different event types for various objects. Ensure the event you are attaching is supported by the target object. For example:

  • Polygon and Polyline support the rightclick event.
  • MVCArray does not support rightclick, making it challenging to attach such an event directly to a vertex.

Tip:​

Always consult the Google Maps JavaScript API documentation to verify event compatibility.

2. Modern GUI Concepts​

When building interactions, remember:

  • Many devices, such as iPads and smartphones, lack traditional mouse functionality.
  • Avoid relying on events like rightclick for core features. Instead, design user interfaces with touch and gesture interactions in mind.

3. Event Attributes​

Google Maps events like MapMouseEvent or PolyMouseEvent lack a button attribute to identify the mouse button used. Instead, use the domEvent property for this information.

Example:​

polygon.addListener("mousedown", (event: google.maps.PolyMouseEvent) => {
const mouseEvent = event.domEvent as MouseEvent;
if (mouseEvent.button === 0) {
console.log("Left mouse button clicked");
} else if (mouseEvent.button === 2) {
console.log("Right mouse button clicked");
}
});

Example: Attaching Event Listeners to Map Objects​

Below is a React component for managing drawing tools and attaching event listeners to polygons and polylines.

import React, { useEffect, useRef, useCallback, useState } from "react";

const addPathListeners = (path: google.maps.MVCArray<google.maps.LatLng>) => {
path.forEach((_, index) => {
google.maps.event.addListener(path, "mouseover", () => {
console.log(`Mouse over vertex ${index}`);
document.body.style.cursor = "pointer";
});

google.maps.event.addListener(path, "mouseout", () => {
document.body.style.cursor = "default";
});
});
};

const attachListenersToEditablePolygon = (polygon: google.maps.Polygon) => {
const path = polygon.getPath();

addPathListeners(path);

google.maps.event.addListener(path, "insert_at", () => addPathListeners(path));
google.maps.event.addListener(path, "remove_at", () => addPathListeners(path));
google.maps.event.addListener(path, "set_at", () => addPathListeners(path));
};

const MapDrawingManager: React.FC<{ mapRef: React.RefObject<google.maps.Map | null> }> = ({ mapRef }) => {
const drawingManagerRef = useRef<google.maps.drawing.DrawingManager | null>(null);

const handlePolygonComplete = useCallback((polygon: google.maps.Polygon) => {
polygon.setOptions({
fillColor: "#0000FF80",
strokeColor: "#0000FF",
strokeWeight: 4,
editable: true,
});

attachListenersToEditablePolygon(polygon);
}, []);

useEffect(() => {
if (mapRef.current && !drawingManagerRef.current) {
const manager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: true,
});

google.maps.event.addListener(manager, "polygoncomplete", handlePolygonComplete);

manager.setMap(mapRef.current);
drawingManagerRef.current = manager;

return () => {
manager.setMap(null);
drawingManagerRef.current = null;
};
}
}, [mapRef, handlePolygonComplete]);

return null;
};

export default MapDrawingManager;

Migrating from google.maps.marker to advancedmarker​

Google has deprecated the google.maps.marker class in favor of the new advancedmarker class. The advancedmarker class offers improved performance and additional features, making it the recommended choice for new projects.

Key Differences:​

  • Performance: advancedmarker is optimized for better performance, especially in applications with a large number of markers.
  • Features: advancedmarker supports advanced features like custom HTML content and improved event handling.

Migration Steps:​

  1. Update Imports: Replace google.maps.marker with google.maps.advancedmarker.
  2. Refactor Code: Update your code to use the new advancedmarker API. This may involve changes to how you create, configure, and interact with markers.
  3. Test Thoroughly: Ensure that your application works as expected after the migration.

Example:​

// Old way using google.maps.marker
const marker = new google.maps.Marker({
position: { lat: -34.397, lng: 150.644 },
map: mapRef.current,
});

// New way using google.maps.advancedmarker
const advancedMarker = new google.maps.advancedmarker.AdvancedMarker({
position: { lat: -34.397, lng: 150.644 },
map: mapRef.current,
});

Best Practices​

  1. Design for Touch-First: Avoid interactions relying on mouse-specific events like rightclick.
  2. Event Verification: Confirm the compatibility of events with the target object.
  3. TypeScript Usage: Leverage TypeScript for better type safety and developer experience.
  4. Code Modularity: Organize logic into reusable functions, such as addPathListeners.
  5. Migrate to advancedmarker: Update your code to use the new advancedmarker class for better performance and features.

Building a Google Maps Application with React and TypeScript

· 3 min read

Prerequisites​

  • Node.js installed (version 14 or higher).
  • npm or yarn for package management.
  • A Google Cloud Platform (GCP) account to obtain the API Key and set up the Map ID.

Project Setup​

  1. Create a React Application:

    npx create-react-app google-maps-app --template typescript
    cd google-maps-app
  2. Install Required Dependencies:

    npm install @react-google-maps/api
    npm install react-hook-form
  3. Setup Google Cloud Platform:

    • Enable the Maps JavaScript API:
      1. Go to the Google Cloud Console.
      2. Create a new project or select an existing one.
      3. Navigate to APIs & Services > Library and enable the Maps JavaScript API.
    • Generate an API Key:
      1. Go to APIs & Services > Credentials and create an API Key.
      2. Restrict the API Key to ensure security by specifying HTTP referrers (your domain or localhost).
    • Create a Map ID:
      1. Go to Google Maps Platform > Maps > Map Management.
      2. Create a new Map ID and configure it with desired styles and settings.

Project Structure​

google-maps-app/
├── public/
├── src/
│ ├── components/
│ │ ├── MapContainer.tsx
│ │ ├── SearchBox.tsx
│ ├── App.tsx
│ ├── index.tsx
│ ├── types/
│ │ ├── index.d.ts
│ ├── utils/
│ ├── mapUtils.ts

Coding the Application​

Step 1: Setup TypeScript Types​

Create src/types/index.d.ts to define types for the Google Maps objects:

declare global {
interface Window {
google: any;
}
}

export interface MarkerData {
position: google.maps.LatLngLiteral;
title: string;
}

Step 2: Utility Functions​

Create src/utils/mapUtils.ts to define helper functions:

export const loadGoogleMapsScript = (apiKey: string): Promise<void> => {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places`;
script.async = true;
script.defer = true;
script.onload = () => resolve();
script.onerror = (e) => reject(e);
document.head.appendChild(script);
});
};

Step 3: Map Container​

Create src/components/MapContainer.tsx:

import React, { useEffect, useRef, useState } from 'react';
import { MarkerData } from '../types';

type MapContainerProps = {
apiKey: string;
mapId: string;
};

const MapContainer: React.FC<MapContainerProps> = ({ apiKey, mapId }) => {
const mapRef = useRef<HTMLDivElement>(null);
const [map, setMap] = useState<google.maps.Map | null>(null);
const [markers, setMarkers] = useState<google.maps.Marker[]>([]);

useEffect(() => {
const initMap = async () => {
try {
await loadGoogleMapsScript(apiKey);
if (mapRef.current) {
const mapInstance = new google.maps.Map(mapRef.current, {
center: { lat: 37.7749, lng: -122.4194 },
zoom: 12,
mapId: mapId,
});
setMap(mapInstance);
}
} catch (error) {
console.error('Failed to load Google Maps:', error);
}
};

initMap();
}, [apiKey, mapId]);

const addMarker = (markerData: MarkerData) => {
if (map) {
const marker = new google.maps.marker.AdvancedMarkerElement({
map,
position: markerData.position,
title: markerData.title,
});
setMarkers((prev) => [...prev, marker]);
}
};

return <div ref={mapRef} style={{ width: '100%', height: '500px' }} />;
};

export default MapContainer;

Create src/components/SearchBox.tsx:

import React, { useEffect, useRef } from 'react';

type SearchBoxProps = {
onPlaceSelected: (place: google.maps.places.PlaceResult) => void;
};

const SearchBox: React.FC<SearchBoxProps> = ({ onPlaceSelected }) => {
const inputRef = useRef<HTMLInputElement>(null);

useEffect(() => {
if (inputRef.current) {
const autocomplete = new google.maps.places.Autocomplete(inputRef.current);
autocomplete.addListener('place_changed', () => {
const place = autocomplete.getPlace();
if (place) {
onPlaceSelected(place);
}
});
}
}, []);

return <input ref={inputRef} type="text" placeholder="Search places..." />;
};

export default SearchBox;

Step 5: Combine Components​

Update src/App.tsx:

import React, { useState } from 'react';
import MapContainer from './components/MapContainer';
import SearchBox from './components/SearchBox';
import { MarkerData } from './types';

const App: React.FC = () => {
const [markers, setMarkers] = useState<MarkerData[]>([]);
const apiKey = 'YOUR_GOOGLE_MAPS_API_KEY';
const mapId = 'YOUR_MAP_ID';

const handlePlaceSelected = (place: google.maps.places.PlaceResult) => {
if (place.geometry?.location) {
const markerData = {
position: {
lat: place.geometry.location.lat(),
lng: place.geometry.location.lng(),
},
title: place.name || '',
};
setMarkers((prev) => [...prev, markerData]);
}
};

return (
<div>
<SearchBox onPlaceSelected={handlePlaceSelected} />
<MapContainer apiKey={apiKey} mapId={mapId} />
</div>
);
};

export default App;

Running the Application​

  1. Replace YOUR_GOOGLE_MAPS_API_KEY and YOUR_MAP_ID in App.tsx with your actual values.
  2. Start the application:
    npm start
  3. Open http://localhost:3000 in your browser.