Changing marker colors dynamically in Google Maps with NextJS

I'm using the @googlemaps/js-api-loader package to load a map in my nextJS app. I have a list of locations that I want to plot on the map, and I also want these locations disabled on the left side of the page.

When hovering over one of the locations in the list, I want to dynamically change the color of the marker representing that location, similar to how the current focus works on the map. How can I achieve this?

This is what my code looks like:

type MarkerObject = {
    id: number
    marker: google.maps.marker.AdvancedMarkerElement
}

export const MapComponent = ({ locations, currentFocusId }: MapProps) => {
    const [markers, setMarkers] = useState<MarkerObject[]>([])

    useEffect(() => {
        const initMap = async () => {
            const loader = new Loader({ apiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY! })
            const { Map } = (await loader.importLibrary('maps')) as google.maps.MapsLibrary

            // create map
            const map = new Map(document.getElementById('map') as HTMLElement, {
                center: locations[0].position,
                zoom: 15,
                mapId: 'map',
            })

            // create markers
            for (const location of locations) {
                const pinBackground = new PinElement({
                    borderColor: 'black',
                    glyphColor: 'black',
                })

                const marker = new AdvancedMarkerElement({
                    map,
                    position: location.position,
                    content: pinBackground.element,
                })
                setMarkers((prev) => [...prev, { id: location.id, marker }])
            }
        }

        initMap()
    }, [])

useEffect(() => {
        if (!markers.length) return

        const focusMarker = markers.find((markerObject: MarkerObject) => markerObject.id === currentFocusId)
        if (!focusMarker) return

        // How can I change or replace the content/color of the marker to make it blue?

    

I have attempted things such as

focusMarker.marker.content = new google.maps.marker.PinElement({
            background: 'blue',
            borderColor: 'black',
            glyphColor: 'black',
        })

but I haven't had any success yet.

Answer №1

Check out this straightforward illustration. If you click the button, it will modify the pin's background color.

  1. Start by creating a PinElement with the desired specifications
  2. Update the properties of the PinElement using dot notation
  3. Apply the adjusted content from the PinElement to the marker's content property

async function initializeMap() {

  // Import necessary libraries.
  const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary(
    "marker",
  );

  const centerCoordinates = {
    lat: 0,
    lng: 0
  }

  const mapInstance = new Map(document.getElementById("map"), {
    center: centerCoordinates,
    zoom: 5,
    mapId: "4504f8b37365c3d0",
  });

  const chosenBackground = new PinElement({
    background: 'red'
  })

  const siteMarker = new AdvancedMarkerElement({
    map: mapInstance,
    position: centerCoordinates,
    content: chosenBackground.element,
    title: "Utilizing PinElement in a marker",
  });
  
  document.getElementById('changePin').addEventListener('click', function() {
    
    // Change background color to "yellow"
    chosenBackground.background = 'yellow'
    siteMarker.content = chosenBackground.element
  });
}

initializeMap();
#map {
  height: 140px;
  margin-bottom: 1em;
}
<div id="map"></div>
<button id="changePin">Adjust pin color</button>

<!-- prettier-ignore -->
<script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
        ({key: "AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk", v: "beta"});</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Differences between encoding URL variables in HREF and using JS window.location for onclick events

For some reason, this particular hyperlink is not functioning properly. I have a Javascript redirect (window.opener.location) where I pass several variables through the URL. The problem arises when these variables contain apostrophes. In PHP, I am using UR ...

How to locate the index of a specific item or multiple items within a JsonArray?

Can you help me determine which city is closest to Vancouver: Victoria, Washington or Texas? Once I find the shortest distance, how can I identify which destination address this value corresponds to? { "destination_addresses" : [ "Victoria, BC, C ...

Tips for modifying the hue of the hint attribute within vue.js?

`<v-text-field id="loginPasswordId" ref="password" v-model="password" class="login-input" dense :disabled="loading" :hint="hello world" :loading="loading" maxlength= ...

When using create-react-app with JEST to run tests, TypeScript errors are not displayed

When I write incorrect TypeScript code in my project set up with create-react-app, running tests using npm test does not show any errors in the terminal. Is this normal behavior? It would be helpful to see these errors to avoid writing incorrect TypeScript ...

Enhance a DOM element using personalized functions in jQuery

Seeking advice on how to create custom widget placeholders with a "setvalue" function specific to each type of widget: $.fn.extend($(".dial"), { setval: function(val) { }); Attempting to avoid extending jQuery.fn directly since different widget type ...

Having trouble with Ajax and facebox integration issues?

My website utilizes ajax jquery and facebox for interactive features. You can check out a demo here. The div with the ID "#content" contains links to other pages that open successfully using facebox. However, when I reload the content of this div using aj ...

When working with Node.js and Express, encountering the error message "data.push is not a

I am encountering an issue when trying to add a new task to the list of all tasks. The error message I receive is TypeError: allTasks.push is not a function data contains JSON data that has been retrieved from a file using the fs method var allTasks = JS ...

Show information based on the user's role

I need to adjust my menu so that certain sections are only visible to specific users based on their roles. In my database, I have three roles: user, admin1, and admin2. For instance, how can I ensure that Category 2 is only visible to users with the ROLE_A ...

Methods for reloading the requirejs module

There are two modules: settingmap.js var settingMap = { scWidth : [4000, 6000, 8000], scHeight : [5000, 7000, 9000], bxWidth : [100, 90, 80], bxHeight : [100, 90, 80], totalTime : [50, 40, 30], level : [1, 2, 3], boxColor : [&a ...

Displaying the most recent queries retrieved from a search API

Our web application built on angular.js utilizes a REST search API to query users within the system. The endpoint for searching users is: search/user?q='abc' Upon revisiting the web application, we aim to display the user's recent search ...

Determining User Login Status in Laravel using jQuery

While I am familiar with the authentication verification in laravel, I am interested in learning how to verify it using jQuery. Specifically, I want to make changes to my CSS when a user is logged in. By default: body{ background: url('image.jpg ...

Encountering a syntax error close to an unexpected token '../lib/cli.js' while attempting to launch an application through pm2 start

I'm encountering an issue while executing pm2 start with an ecosystem.config.js /root/.nvm/versions/node/v18.16.0/bin/npm: line 2: require('../lib/cli.js')(process)' /root/.nvm/versions/node/v18.16.0/bin/npm: line 2: syntax error near u ...

Leveraging Parameters from URL in Javascript

I'm facing an issue with my area shape, the href="/kosmetikstudios/deutschland/Bayern" tag seems to be causing a problem. I want to utilize the parameter "Bayern" (which is the last parameter in the URL). I need this to be dynamic. Below is my JavaS ...

The issue of accessing the session before scripts are loaded arises when using VueJS alongside Firebase Authentication

Currently grappling with a project where I'm facing some challenges... I've opted for VueJS on the frontend and implemented Firebase Authentication for user login. I'm trying to determine the login status of a user by using firebase.auth(). ...

I encountered a CORS issue even though I had set up CORS on my ASP.NET Core Web API application

I am encountering an issue with CORS while trying to make a fetch request from my web app hosted on Vercell to my ASP.NET Core Web API in Azure. The error I'm getting is: Access to fetch at {myapi enpoint} from origin 'https://{myapp}.vercel.ap ...

I'm facing an issue with the code within the script tag in my Next.js application - can anyone

I have a file named 'blog.js' located in the pages folder, and another file called 'al.js' in the public folder. Below is the code snippet from my blog.js file: import React from 'react'; import Head from 'next/head' ...

When implementing dynamic imports in Next.js, the router.push method with the shallow:true option does not function correctly and always results in a page refresh

I am currently utilizing Next 12.1 My approach involves using dynamic imports to import Components. I am trying to utilize the feature router.push with shallow:true. However, whenever I call router.push (with shallow:true), the component always re-render ...

Obtaining JSON Data Using WinJS.xhr():

I'm encountering difficulties with retrieving chat messages using winjs.xhr: function getMessage() { var time = MESSAGE_RETURNED.unixtime; if (time == 0) { time= window.parent.SESSION.unixtime; } WinJS.x ...

Tackling JavaScript: Exploring Ternary Short Circuit and If Short Circuit

I am attempting to optimize the code by using a ternary operator to quickly return false. My understanding was that using a ternary in this scenario would have the same outcome as the if statement below it, which is to instantly return false if the lengths ...

html5-jquery checkbox change event not firing

I successfully implemented an on/off switch using the method outlined in for HTML5. The functionality of the switch itself is working perfectly - click on it to toggle between states and query the checked state of the input/checkbox. However, I am facing ...