In this article, we will make an ionic react google maps application with custom markers. How to integrate Google maps within ionic. It is a two-part series, and in this article, we will learn how to create custom markers in our Ionic 6 google maps application.

Outline

Getting Started

For this tutorial, you will need basic knowledge of programming. Firstly, we need to get a Google Maps API key in order to make requests to the Maps Javascript API.

Creating our API

  1. Visit the Google Developer Console and login using your Google account.
  2. Click the dropdown on Select a project and click on New Project.
  3. Name the project, leave the organization option as is. Click Create. I am naming the project codeswag-map-demo.
  4. The project is open. Click on Enable APIs and Services.
  5. We are redirected to the API library and click on Maps Javascript API here.
  6. Click Enable.
  7. After API has been enabled, we want to click on Credentials and then click on Credentials in APIs & Service.
  8. When the page loads, click on Create Credentials and select API key. Our API key is created,
    copy it, and save it in a safe location.

Creating a new Ionic 6 project

We want to create a new Ionic 6 project. Open cmd (command prompt) and run the following command:

ionic start

I will use react as our framework, codeswag-map-react as the project name, and blank as our starter template.

framework: react
project name: codeswag-map-react
starter template: blank

On the integrate with capacitor prompt, type **y'** for yes and pressenter`, but we will not be using it.

And with that, we have created our Ionic 6 project.

In the command line, navigate into the project folder and open the project in Visual Studio Code by running the following commands.

cd codeswag-map-react
 code .

Running the App

Head back to the command line in our project folder; we need to run the command:

ionic serve

blank app

Creating the Map Component

First we need to install @react-google-maps/api. It provides very simple bindings to the google maps api and lets you use it in your app as React components.

Head over to the console and in the project folder execute the following command.

npm i -S @react-google-maps/api

Next, we create a Map component and add the following code to create our functional component.

import React, { useState } from 'react';

const Map: React.FC = () => {}

export default Map;

Next, let’s add the Map component to our home page. Open Home.tsx and import the Map component.

import Map from './../components/Map';

Then render the Map component in the IonContent tag.

<IonContent fullscreen>
    <Map />
</IonContent>

Next, we want to render the map.

Adding the Map to our Application

Head back to Map.tsx. Import GoogleMap and the useLoadScript from @react-google-maps/api.

import { GoogleMap, useLoadScript } from '@react-google-maps/api';

Next, we create a property to load the google maps API using useLoadScript. We provide the API key we copied in our earlier steps.

const { isLoaded } = useLoadScript({ googleMapsApiKey: "YOUR_API_KEY" });

Next, we load the Google Map with the given API key. The map will display a loading message if it has not been loaded yet. Otherwise we create an instance of the GoogleMap component with the following attributes: – zoom={15} - center={{ lat: -17.8318, lng: 31.0474 }}

The code then places this map in a tag and adds it to the page. We are creating a map with the center coordinates of -17.8318, 31.0474, and zoom level 15.

if (!isLoaded) return <div>Loading...</div>

    return (
        <GoogleMap
            zoom={15}
            center={{ lat: -17.8318, lng: 31.0474 }}
            mapContainerClassName="map-container"
        ></GoogleMap>
    )

Next, we head over to Home.css to set the height of the map container. If we do not do this the map won’t appear. It has a height of 0 by default.

.map-container {
    height: 100vh;
    width: 100%;
}

ionic react google maps

Custom Map Marker Data

In the src folder, add a new folder called data, and in the data folder, create a marker.ts file. We are adding the code below for our marker information in this file.

export const markers: any = [
  {
    id: 1,
    title: 'Natonal Art Gallery',
    latitude: -17.8249,
    longitude: 31.0490
  },
  {
    id: 2,
    title: 'West End Hospital',
    latitude: -17.8208,
    longitude: 31.0395
  },
  {
    id: 3,
    title: 'Dominican Convent School',
    latitude: -17.8224,
    longitude: 31.0524
  },
  {
    id: 4,
    title: 'Chop Chop Brazilian Steakhouse',
    latitude: -17.8202,
    longitude: 31.0542
  }
];

Head back to Map.tsx to create the Markers.

Adding Custom Markers

Next, import the list of markers and the MarkerF component from @react-google-maps/api. We will use the marker component to create a google maps marker.

import { GoogleMap, useLoadScript, MarkerF } from '@react-google-maps/api';
import { markers } from '../data/markers';

Below the isLoaded variable, let’s create a function to handle the markers. We use the map method to loop through the markers list, and we map each marker to a single MarkerF component which takes in the latitude and longitude and renders it on our map.

<MarkerF key={marker.id} position={{ lat: marker.latitude, lng: marker.longitude }}></MarkerF>

Next, we pass in the function in the GoogleMap component.

<GoogleMap
            zoom={15}
            center={{ lat: -17.8318, lng: 31.0474 }}
            mapContainerClassName="map-container"
        >
            {handleCustomMarkers()}
        </GoogleMap>

custom markers

Adding the Info Window

Now we want to add an Info Window for our custom markers. When a user clicks on a marker, they should get the marker title along with its latitude and longitude.

The first step is to create a state to manage the id of the clicked marker.

const [markerId, setMarkerId] = useState(null);

Next, we create a method to get the id of the clicked marker and set it as the new markerId value.

const handleInfoWindow = (id: any) => {
        setMarkerId(id);
}

We then add an onClick attribute in our custom markers and pass a reference to this method.

<MarkerF onClick={() => handleInfoWindow(marker.id)} key={marker.id} position={{ lat: marker.latitude, lng: marker.longitude }}></MarkerF>

Now to show the info window when we click a marker, we add an if statement in the MarkerF tag.

After clicking a marker, if the value of the markerId state is the same as the marker.id being rendered, then it opens an Info Window for that marker showing the marker title, latitude, and longitude.

{markerId === marker.id ? (
    <InfoWindowF position={{ lat: marker.latitude, lng: marker.longitude }}>
        <div className='info-window'>
            <h2>{marker.title}</h2>
            <p className='paragraph'>Latitude: {marker.latitude}</p>
            <p className='paragraph'>Longitude: {marker.longitude}</p>
        </div>
    </InfoWindowF>) : null}

To use the InfoWindowF component, we also need to import it from react-google-maps/api.

import { GoogleMap, useLoadScript, MarkerF, InfoWindowF } from '@react-google-maps/api';

By default the text color for the Info Window contents is white so nothng will appear. To fix this let’s head over to Home.css and set the text color to black.

.info-window {
    color: #000;
}

And we are done! Let’s try it out in the browser.

custom markers

map with info window open

Next, we will implement turn-by-turn navigation in our ionic application.

Turn-By-Turn-Navigation

Turn-by-turn Navigation is a feature where a user is continuously presented with the directions of a selected route in the form of visual or spoken instructions till they reach their intended destination.

turn by turn navigation

The first thing we are to do is to add an IonButton to our Info window. When we click it, it will hand over navigation to the Google maps application.

Import IonButton from ionic/react.

import { IonButton } from '@ionic/react';

Next, let’s add the IonButton to the Info Window and we will label the button Navigate.

<InfoWindowF position={{ lat: marker.latitude, lng: marker.longitude }}>
    <div className='info-window'>
        <h2>{marker.title}</h2>
        <p className='paragraph'>Latitude: {marker.latitude}</p>
        <p className='paragraph'>Longitude: {marker.longitude}</p>
        <IonButton >Navigate</IonButton>
    </div>
</InfoWindowF>

Next, we want to add a method to handle the click event for the IonButton. The method takes in two parameters, latitude and longitude, for the marker we want directions to.

const handleNavigation = (lat:any, lng:any) => {
    window.open(`https://www.google.com/maps/dir/?api=1&destination=${lat},${lng}`);
}

This code hands off the navigation from your ionic application onto the Google Maps application. If you have google maps installed on your device, it will hand over to the google maps application. If you do not have google maps installed, it will open via the web browser.

Next, add an onClick attribute to the IonButton and pass a reference to the handleNavigation method.

<IonButton onClick={() => handleNavigation(marker.latitude, marker.longitude)}>Navigate</IonButton>

And we are done! Let’s check it out in the browser.

navigate button

turn by turn navigation

Running the application on the Android Emulator

Open the terminal and cancel the process running ionic in our browser by pressing:

CTRL + C

We will use capacitor to run our application in our Emulator to see what our default application looks like on a device.

First we will install capacitor android platform.

npm install @capacitor/android

Next, we will build our application.

ionic build

That is going to prepare the necessary files for feeding into capacitor. Next, we run the command:

npx cap add android

That is going to add the android dependencies to our project. Next, we can run the following command:

npx cap open android

info window

If we click the navigation button, Google Maps Application is opened.

google maps

turn by turn navigation

Conclusion

Alright! We have successfully made an ionic application with google maps API integrated into it. We learned how to create an API key for google maps API and how to create and add custom markers on our map. We also learned how to implement information windows for our custom markers on our map, and implement turn by turn navigation.