Modify the Google Maps icon based on the type of data within an array dynamically

Being new to the world of JavaScript, I've been given the task of converting an old jVector map to the Google Maps API. Surprisingly, I think I'm making good progress! I've successfully populated the map with the right markers in their assigned locations, complete with stylish info windows that pop up when clicked. Everything seems to be working well at this point.

However, I've hit a bump in the road while attempting to dynamically change Google Maps icons upon map load, depending on whether a string from an array matches one of 8 different types. The specific code snippet I've been struggling with is as follows:

Data Array Example

The array contains around 30 stories, but for clarity, I'm omitting the content and providing the code structure below:

 var stories = [
    // ACT Markers 
    // ACT ICT
    {
        latlng: [-35.3449476, 148],
        name: "Business name - tagline after the business name",
        type: "ICT",
        text: 'some basic text marked up with html',
           },

Main Code Example:

window.onload = function() {
    LoadMap();
};

function LoadMap() {
    var mapOptions = {
        center: new google.maps.LatLng(-25.363882, 131.044922),
        zoom: 4,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map-content"), mapOptions);

    for (var i = 0; i < stories.length; i++) {
        var storydata = stories[i];
        var myLatLng = new google.maps.LatLng(storydata.latlng[0], storydata.latlng[1]);
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map,
            title: storydata.name,
            content: storydata.text,
        });

        var infowindow = new google.maps.InfoWindow();

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(this.title + this.content);
            infowindow.open(map, this);
        });
    }

Everything has been functioning smoothly so far, but there might be a more efficient way to achieve this. Given my novice status in JavaScript, I'm open to suggestions or improvements.

Categorization Challenge:

Now, I'd like to change the icon based on the "type" attribute within "stories". I've been experimenting with the following code snipped sourced from various Stack Overflow threads (apologies for not having the links), but I'm unsure where to insert it or if I'm even on the right track:

for (var item in stories) {
    if (stories[i].type == 'Agrifood') iconString = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png';
    else if (stories[i].type == 'Biotechnology') iconString = 'http://maps.google.com/mapfiles/ms/icons/pink-dot.png';
    else if (stories[i].type == 'BuiltEnvironment') iconString = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png';
    else if (stories[i].type == 'Energy') iconString = 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png';
    else if (stories[i].type == 'Engineering') iconString = 'http://maps.google.com/mapfiles/ms/icons/purple-dot.png';
    else if (stories[i].type == 'ICT') iconString = 'http://maps.google.com/mapfiles/ms/icons/ltblue-dot.png';
    else if (stories[i].type == 'Manufacturing') iconString = 'http://maps.google.com/mapfiles/ms/icons/orange-dot.png';
    else if (stories[i].type == 'Mining') iconString = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png';
    else iconString = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png';
}

I would greatly appreciate any guidance or assistance you can offer in solving this issue. Thank you very much!

Answer №1

To improve your code, consider making the following adjustments:

for (let index = 0; index < stories.length; index++) {
    let data = stories[index];
    let iconPath = '';
    
    switch (data.type) {
        case 'Agrifood':
            iconPath = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png';
            break;
        case 'Biotechnology':
            iconPath = 'http://maps.google.com/mapfiles/ms/icons/pink-dot.png';
            break;
        case 'BuiltEnvironment':
            iconPath = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png';
            break;
        case 'Energy':
            iconPath = 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png';
            break
        case 'Engineering':
            iconPath = 'http://maps.google.com/mapfiles/ms/icons/purple-dot.png';
            break;
        case 'ICT':
            iconPath = 'http://maps.google.com/mapfiles/ms/icons/ltblue-dot.png';
            break;
        case 'Manufacturing':
            iconPath = 'http://maps.google.com/mapfiles/ms/icons/orange-dot.png';
            break;
        case 'Mining':
            iconPath = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png';
            break;
        default:
            iconPath = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png';
    }
    
    let newLatLng = new google.maps.LatLng(data.latlng[0], data.latlng[1]);
    let marker = new google.maps.Marker({
        position: newLatLng,
        map: map,
        icon: iconPath,
        title: data.name,
        content: data.text
    });
   
    let infoWindow = new google.maps.InfoWindow();

    google.maps.event.addListener(marker, 'click', function () {
        infoWindow.setContent(this.title + this.content);
        infoWindow.open(map, this);
    });
}

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

Switch the dropdown menu to a button if it consists of only one option

I have been using a database within the Moodle Learning Management System that generates a bootstrap table. Here is an example of what it looks like: The last row in the table contains a dropdown menu. When viewing your own entry, you have the options to ...

"Navigate with ease using Material-UI's BottomNavigationItem and link

What is the best way to implement UI navigation using a React component? I am currently working with a <BottomNavigationItem /> component that renders as a <button>. How can I modify it to navigate to a specific URL? class FooterNavigation e ...

Printing a React component using a button causes formatting related to className to be lost, while printing it inline preserves the formatting

I've hit a roadblock in trying to figure out the React and printing issue for the past week and a half, and it feels like I'm going in circles. Despite finding some helpful solutions on Stack Overflow, none of them seem to work completely for me ...

Utilizing AJAX for seamless communication between JavaScript and PHP within a modal dialogue box

I'm struggling with learning how to effectively use ajax. In the project I'm currently working on, I have a chart where I can select different people. Once I click on a person's button, their information gets updated in the database. However ...

After reducing the size of the table, the data spills over

Hey there, amazing individuals of the internet! Hope you're all doing well today. I've encountered a rather perplexing issue that's got me stumped. So, here's the situation - I have this table full of data and I want it to initially be ...

Divide a JSON dataset into two distinct JSON files and incorporate them within the code

My JSON file structure is as follows: { "rID": "1", "rFI": "01", "rTN": "0011", "rAN": "11", "sID&quo ...

Challenges with dividing input into array indices in C programming

Currently, I am diving into the world of C programming and facing an issue with splitting a string of text. My goal is to prompt the user to input multiple words separated by spaces in a single line, and then have the program split these words and store ...

The useMutation function trapped in an endless loop

I've been encountering an issue while running a query to save an entity in the database using usemutation. The saveVisa() mutation seems to be stuck in an infinite loop, creating the same element multiple times without any clear reason. import {React, ...

Interactively retrieving objects from a JavaScript array based on their keys

let arr = [{id:'one',val:1},{id:'two',val:2}] for( let ii of arr ) { if( ii.hasOwnProperty('id') ) arr[ii.id] = ii } This code snippet allows for accessing the elements in the array by their 'id' key. For exampl ...

The initial update of ng-model is not occurring

I am currently working on a checkbox functionality in my project that is bound to an ng-model: <input type="checkbox" ng-change="toggleAll(globalChecked)" ng-model="globalChecked"> The toggleAll function is responsible for accessing the globalCheck ...

Error encountered with Next.js and Square API: The Fetch API cannot load due to the unsupported URL scheme "webpack-internal"

I encountered an issue while attempting to retrieve stock data from the Square API. injectGlobalHook.js:1648 Fetch API cannot load webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ReactDevOverlay.js. URL scheme "webpack-internal ...

What advantages come from caching the document object for improved performance?

Usually, I cache DOM objects used in a script. However, recently I found myself having to reference the document object within a jQuery wrapper. I started questioning whether caching $(document) is necessary since there's only one document object per ...

How can I create a PHP associative array with dynamically generated values inside a for loop without causing chaos?

In an interesting twist, the following PHP code snippet: $retVal = array(); $numberedWrapper = array(); for ($i=0; $i<$amount; $i++) { while (!$this->checkUsername($username, $retVal, $services)) ...

Several JavaScript functions require a confirmation dialog to be displayed before they can be executed

There are three separate javascript/jquery functions in my code, all triggered by a button click. One function posts to a form handler, another creates a new tab, and the third one sends new data into the tab through an ajax call. These functions are inter ...

Stop the annoying page flicker in Next.js 12 by implementing a custom dark mode using Tailwind CSS classes

Is there a way to prevent the page flash when implementing dark mode in Tailwind CSS using classes in Next.js v12 without relying on third-party packages like next-themes? I have explored different solutions: This StackOverflow Q&A How to fix dark mo ...

What are the steps for showcasing a personalized HTML tag on a web page

I need to capture user input text and display it correctly. This is what I have attempted: <div> <input type="text" ng-model="post.content" /> </div> <div> <div ng-bind-html="post.content| htmlize"></div> < ...

Ways to clearly establish the concept of "a"

module.exports.getData = function (id) { const userData = require("./data/Users.json"); if (userData.find(user => user.uid === id)) { return user.name; } else return "User"; } I'm trying to display the name of a user, but the consol ...

A guide to troubleshooting the error 'response.json is not a function' within an async/await function

Having trouble converting my response to JSON. I keep receiving a TypeError: response.json is not a function error. Can someone please help me figure out what's going wrong? Thanks in advance. componentDidMount(){ this.timingFunction = se ...

Is it possible to process HTML and JavaScript as a request in JMeter?

After receiving a response, I noticed that the HTML body contains a hidden form along with an internal JavaScript function to submit the form (view snapshot here). Is there a method in JMeter to execute JavaScript code that directly submits a form? I am ...

Convert an array with three dimensions into a two-dimensional array that includes tuples with two immutable string values

Consider the array below with multiple dimensions: type ParsedLine = [string, string]; type ParsedLines = [ParsedLine, ParsedLine] const myArray: (ParsedLine | ParsedLines)[] = [ ['something', 'somethingElse'], [['foo', & ...