Unleashing the Power of Google Maps API in Your React App

darkterminal avatar
GitHub Account@darkterminal
LanguageJAVASCRIPT
Published At2023-04-04 15:02:39

The Back Story about your Javascript Metaphor

Hello punk, location-based apps have become increasingly popular, and the Google Maps API is a fundamental tool for developers to build apps that require location services. However, integrating Google Maps API with a React application can be a challenge. In this metaphor story, I will explore how to use the Google Maps API in a React app to create a MapLine component that displays a line between two points on the map. We will also discuss a utility function called toObjectCoordinate that converts a latitude and longitude string into an object with lat and lng properties.

The javascript Story!

The Brief

Google Maps API is a powerful tool that provides developers with a range of location-based services to integrate into their applications. The MapLine component I will write in in this metaphor story uses the Google Maps API to display a line between two points on the map. I will use the useEffect hook in React to load the API and create the map, and the useRef hook to get a reference to the HTML element that will display the map.

The MapLine Component

The MapLine component takes several props, including an:

  • API key
  • the center point of the map
  • the zoom level
  • and an array of points that define the line.

In my example, I use the toObjectCoordinate utility function to convert two latitude and longitude strings into objects with lat and lng properties.

1<MapLine
2    apiKey={maps.key}
3    center={toObjectCoordinate(currentLocation, true)}
4    points={[
5      toObjectCoordinate(currentLocation, true),
6      toObjectCoordinate(modalData.customerCoordinate, true),
7    ]} 
8    zoom={10}
9/>

The Utility

The toObjectCoordinate function takes a latitude and longitude string as an argument and returns an object with lat and lng properties. The second argument is a boolean that indicates whether the function should convert the string values to numbers or return them as strings. The function splits the string by comma and returns an object with lat and lng properties.

1export default function toObjectCoordinate(latLong, toNumber = false) {
2    const index = latLong.split(',')
3    return {
4        lat: toNumber ? Number(index[0]) : index[0],
5        lng: toNumber ? Number(index[1]) : index[1],
6    }
7}

Implementation

The useEffect hook in the MapLine component loads the Google Maps API using the Loader object provided by the @googlemaps/js-api-loader package. Once the API is loaded, we create a new instance of the google.maps.Map object, set the center and zoom level, and add a new google.maps.Polyline object that represents the line between the two points. I also create a new google.maps.Marker object for each point on the line and add them to the map.

1import React, { useEffect, useRef } from 'react';
2import { Loader } from '@googlemaps/js-api-loader';
3
4const MapLine = ({ apiKey, center, zoom, points, twStyle = 'w-full h-52' }) => {
5    const mapRef = useRef(null);
6
7    useEffect(() => {
8        const loader = new Loader({
9            apiKey: apiKey,
10            version: 'weekly',
11        });
12
13        loader.load().then(() => {
14            if (mapRef.current instanceof Element) {
15                const map = new google.maps.Map(mapRef.current, {
16                    center: center,
17                    zoom: zoom,
18                });
19
20                // Create a new line from point A to point B
21                const line = new google.maps.Polyline({
22                    path: points,
23                    geodesic: true,
24                    strokeColor: '#FF0000',
25                    strokeOpacity: 1.0,
26                    strokeWeight: 2,
27                });
28
29                // Set the line on the map
30                line.setMap(map);
31
32                const bounds = new google.maps.LatLngBounds();
33                points.forEach((point) => bounds.extend(point));
34                map.fitBounds(bounds);
35
36                // Add a marker to each point on the line
37                points.forEach((point) => {
38                    new google.maps.Marker({
39                        position: point,
40                        map: map,
41                    });
42                });
43
44                // Hide the map control
45                map.setOptions({ disableDefaultUI: true });
46            }
47        });
48    }, [apiKey, center, zoom]);
49
50    return <div ref={mapRef} className={twStyle} />;
51};
52
53export default MapLine;

The Conclusion

In conclusion, Google Maps API is a powerful tool for developers to create location-based applications. Integrating Google Maps API with a React application can be challenging, but using the useEffect and useRef hooks in combination with the @googlemaps/js-api-loader package can make the process smoother. The MapLine component discussed in this metaphor story uses the Google Maps API to display a line between two points on the map and utilizes a toObjectCoordinate utility function that converts a latitude and longitude string into an object with lat and lng properties. With this knowledge, developers can unlock the power of Google Maps API in their React applications.

image

A Javascript demo/repos link

No response

PayPal Link for Donation (Javascript Storyteller)

https://www.paypal.me/lazarusalhambra

Share This Story