"Modify marker icon upon click event in Google Maps by utilizing the loadGeoJson function

I have successfully loaded the markers from a json file using loadGeoJson.

While I am able to SET the marker icon/img on load, I am unsure of how to CHANGE it upon click.

Is there a way to target the clicked marker and perform a setIcon or similar action?

Javascript:

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 6,
      center: new google.maps.LatLng(2.8,-187.3),
      mapTypeId: 'terrain'
    });

    map.data.loadGeoJson('geoJson2.json'); 

    map.data.setStyle(function(feature) {
      return {icon:feature.getProperty('icon')};
    });

    map.data.addListener("click", event => {
      console.log(event.feature.getProperty("hicon"));
        //CHANGE MARKER ICON -> event.feature.getProperty("hicon")

    });
}

Json:

{
   "type":"FeatureCollection",
   "features":[
      {
         "type":"Feature",
         "properties":{
            "name":"nameOne",
            "icon":"marker1.png",
            "hicon":"marker1HOVER.png",
            "id":1
         },
         "geometry":{
            "type":"Point",
            "coordinates":[
               -59.58984374999999,
               -37.97884504049711
            ]
         }
      }
   ]
}

Answer №1

Check out the dynamic styling example in the official documentation.

  map.data.setStyle(function(feature) {
    var icon = feature.getProperty('icon');
    if (feature.getProperty("isHighlighted"))
      icon = feature.getProperty('hicon');
    return {
      icon: icon
    };
  });

  map.data.addListener("click", event => {
    if (!event.feature.getProperty("isHighlighted"))
      event.feature.setProperty("isHighlighted", true);
    else 
      event.feature.setProperty("isHighlighted", false);
    console.log(event.feature.getProperty("hicon"));
    //CHANGE MARKER ICON -> event.feature.getProperty("hicon")

  });

See the proof of concept fiddle here

Snippet of code:

"use strict";

let map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 6,
    center: new google.maps.LatLng(-37.9788, -59.58984375),
    mapTypeId: 'terrain'
  });

  map.data.addGeoJson(geoJson);

  map.data.setStyle(function(feature) {
    var icon = feature.getProperty('icon');
    if (feature.getProperty("isHighlighted"))
      icon = feature.getProperty('hicon');
    return {
      icon: icon
    };
  });

  map.data.addListener("click", event => {
    if (!event.feature.getProperty("isHighlighted"))
      event.feature.setProperty("isHighlighted", true);
    else
      event.feature.setProperty("isHighlighted", false);
    console.log(event.feature.getProperty("hicon"));
    //CHANGE MARKER ICON -> event.feature.getProperty("hicon")

  });
}
var geoJson = {
  "type": "FeatureCollection",
  "features": [{
    "type": "Feature",
    "properties": {
      "name": "nameOne",
      "icon": "https://maps.google.com/mapfiles/ms/micons/blue.png",
      "hicon": "https://maps.google.com/mapfiles/ms/micons/yellow.png",
      "id": 1
    },
    "geometry": {
      "type": "Point",
      "coordinates": [-59.58984374999999, -37.97884504049711]
    }
  }]
};
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>

<head>
  <title>Data Layer: Styling</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly" defer></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="map"></div>
</body>

</html>

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

What is the fewest amount of commands needed to generate a client-side Javascript code that is ready for use?

In the realm of JavaScript libraries found on Github, it has become increasingly challenging to integrate them directly into client-side projects with a simple script tag: <script src="thelibrary.js"></script> The issue arises from the browse ...

The Chrome Extension XHR always gets a 403 response except when it is triggered from the file:/// protocol

My current project involves the development of a Chrome Extension that relies on the fixer.io API for accessing currency exchange rates. To test this extension, I typically use a simple HTML page where I embed my JavaScript using <script> tags. When ...

What are the steps to design a versatile gallery page that can serve various projects?

Allow me to get straight to the point. What is my goal? I am aiming to develop galleries for various projects. Each project's thumbnail on the main page should open a gallery as a new page. These galleries will all have the same layout but different ...

AJAX forms and snippets

I have successfully integrated comments into public activity following a tutorial on public activity #406 Public Activity. However, I am facing issues with submitting the comments via ajax. I have gone through several tutorials but haven't been able t ...

Creating a PHP JSON response that incorporates an HTML layout is a dynamic

I'm having some trouble with a certain issue: I am attempting to develop a jQuery/AJAX/PHP live search bar. Although I am successfully calling search.php, the response displayed in the console always includes the contents of my master.php file (which ...

Emphasize the designated drop zone in Dragula

Incorporating the Dragula package into my Angular 2 project has greatly enhanced the drag-and-drop functionality. Bundling this feature has been a seamless experience. Visit the ng2-dragula GitHub page for more information. Although the drag-and-drop fun ...

displaying only the date in bootstrap-datetimepicker

I am currently utilizing the repository created by smalot, and my intention is to choose and display dates only (while in other instances I showcase both date and time, hence utilizing this repository). Although I have succeeded in selecting dates only, th ...

Is there a way to ensure that the 'pointermove' event continues to trigger even after the dialog element has been closed?

I am working on a project that involves allowing users to drag elements from a modal dialog and drop them onto the page. I have implemented a feature where dialog.close() is called once the user starts dragging. This functionality works perfectly on deskto ...

Effortless Page Navigation - Initial click may lead to incorrect scrolling position, but the subsequent link functions perfectly

While implementing the Smooth Page Scroll code from CSS Tricks, we encountered an issue where clicking on a navigation link for the first time only scrolls down to a point that is approximately 700px above the intended section. Subsequent clicks work perfe ...

What is the purpose of running "npm install" if the "node_modules" directory already exists?

When "npm install" is run on a project directory containing both a "package.json" file and a "node_modules" directory, what impact does it have? Does it replace the current modules with newer versions? Does it update them, or does it have no effect at all ...

Encountering a Component Exception error in React Native while attempting to implement a Victory chart component

Currently, I am exploring the Victory library for react native to create a line chart for my budgeting application. Below is the code snippet from my Graph component: import React from 'react'; import { View, StyleSheet } from 'react-native& ...

Gatsby: A guide on inserting unadulterated HTML within the head section

Is it possible to insert raw HTML into the <head></head> section of every page in a Gatsby.js project? I need to add a string of HTML for tracking purposes, including inline and external script tags, link tags, and meta tags. For example, here ...

How can I hide a root layout component in specific nested routes within the app directory of Next.js?

Is there a way to prevent rootlayout from being wrapped around dashboardlayout? Explore the latest documentation for Next.js version v13: Take a look at my file structure: I considered using route groups, but that approach disabled wrapping in the contac ...

Using an npm package in client-side JavaScript

I've been exploring client-side GitHub packages recently and came across developers mentioning that the packages can be downloaded using npm. This confuses me as I thought these were client-side JavaScript packages. They also mentioned something about ...

Error in AngularJS when attempting to use an expression as a parameter for a function, resulting in a syntax parse

Encountering an issue while attempting to parse this code snippet. I need to pass an expression as a parameter in the ng-click function, but it's not allowing me to do so. If I don't use an expression, then clicking on the album image will clear ...

Analyze and tally occurrences in two arrays

I have two arrays $array1=('18753933','18753933','18771982') $array2=('18753933','18771982') My goal is to compare the values that are the same in both arrays. var countArticlesLoaded=0; for(var $i=0;$i ...

New and personalized bindings in knockout.js for dynamically updating a dropdown menu based on the selection in another dropdown menu

I have been using knockout for a few months now and have been getting along just fine. However, I recently encountered an issue where I cannot update the options within a SELECT tag because the ajax methods that retrieve data from the server are inside a ...

Creating a Draft.js selection with a specified start and end point

Looking for a way to replace the last insertion in Draft.js For instance, Original string -> aaazzz After inserting 'bbb' in the middle -> aaabbbzzz Replace last insert with 'ccc' -> aaaccczzz Replace last insert with &apos ...

How can I loop through JSON in AngularJS to populate fields without knowing the key value?

Here is the data structure that I'm working with: { "0": { "keyword": "flower", "short_desc": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "pt_value": "5" }, "1": { "keyword": "tree", "short_desc": "Lorem ipsum dolor sit amet, consecte ...

Generate a new style element, establish various classes, and append a class to the element

Is there a more efficient solution available? $("<style>") .attr("type", "text/css") .prependTo("head") .append(".bor {border:2px dotted red} .gto {padding:10px; font-size:medium}"); $("input:text").addClass("bor gto").val("Enter your t ...