Trying to assign marker image dynamically through various database inquiries

With the use of the Google Maps API v3, I am currently displaying a map of the United States with markers placed at specific locations obtained from address queries in my Postgres database. My goal is to customize the marker image based on the result of each query. Although I have successfully created two separate objects for these queries and logged them individually, I am struggling to utilize this information to determine which markers are shown.

var labels = '';
var iconBase = 'green.png';
var iconBaseRed = 'red.png';

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {

if (xhr.readyState == 4) {
var arr = JSON.parse(xhr.responseText);
console.log(xhr.responseText);
if(Array.isArray(arr)){
showMarkers(arr);
}
}
}
xhr.open('GET', 'markers.php', true);
xhr.send();

function showMarkers(locations){
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
icon: iconBase,
label: labels[i % labels.length]
});
});

var markerCluster = new MarkerClusterer(map, markers,
        {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
  }


var xhrred = new XMLHttpRequest();
xhrred.onreadystatechange = function() {

if (xhrred.readyState == 4) {
var arrred = JSON.parse(xhrred.responseText);
console.log(xhrred.responseText);
if(Array.isArray(arrred)){
showMarkers(arrred);
}
}
}
xhrred.open('GET', 'markersred.php', true);
xhrred.send();


function showMarkers(locations){
var markersRed = locations.map(function(locationred, i) {
return new google.maps.Marker({
position: locationred,
icon: iconBaseRed,
label: labels[i % labels.length]
});
});

var markerClusterRed = new MarkerClusterer(map, markersRed,
        {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});

  }

I initially tried creating distinct variables for each XMLHttpRequest to generate multiple JSON objects. Unfortunately, when attempting a similar approach with the showMarker function, it did not yield the desired outcome. This is where my issue lies... Any assistance would be greatly appreciated.

For testing purposes, you can access the link below (refer to console log for data): www.rightmediasolutions.com/gs_chrome/testing.html

Currently, only the iconBaseRed marker is being displayed.

Answer №1

It seems like you are handling two separate ajax requests, each returning an array of locations. Your goal is to show different marker icons based on which ajax call the data is coming from.

A better approach could be passing the marker icon as a parameter in your function:

function displayMarkers(locations, customIcon){
    var markers = locations.map(function(location, index) {
        return new google.maps.Marker({
            position: location,
            icon: customIcon,
            label: labels[index % labels.length]
    });
});

Then, when processing the results of each ajax call, use displayMarkers with the corresponding icon:

displayMarkers(arrayOne, iconOne);
displayMarkers(arrayTwo, iconTwo);

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

Why isn't data coming through after sending ajax post requests?

Why am I unable to retrieve data after sending AJAX post requests? During the process of sending an AJAX post request, I use $('#fid1 input,select').attr('disabled','disbaled'); to disable form inputs and then, after a suc ...

Ensure that every item in the list is assigned a distinct "key" prop to avoid duplication. Follow these steps to address the issue

function App() { return <StrictMode>{data.map(createCard)}</StrictMode> } function createCard(characters) { return ( <Card id={characters._id} name={characters.name} about={characters.about} img={characters.im ...

maxCalendar - Retrieve outcomes without relying on indexOf()

Good day! I have a property in my code that utilizes the eventRender function to return events based on a specific keyword input by the user. While this works well for exact matches, I am striving to enhance it to include partial matches such as letters o ...

In PhantomJS, where is the location of the "exports" definition?

Consider the following code snippet from fs.js: exports.write = function (path, content, modeOrOpts) { var opts = modeOrOptsToOpts(modeOrOpts); // ensure we open for writing if ( typeof opts.mode !== 'string' ) { opts.mode = ...

Locate the generated ID of the inserted child when saving the parent in MongoDB

If I have a document representing a post with comments like the one below: { "_id": "579a2a71f7b5455c28a7abcb", "title": "post 1", "link": "www.link1.com", "__v": 0, "comments": [ { "author": "Andy", "body": "Wis ...

The performance of my SVG Filter is dismal

Here is the SVG filter I am using: <svg style="visibility: hidden; height: 0; width: 0;"> <filter id="rgbShift"> <feOffset in="SourceGraphic" dx="1" dy="-1" result="text1" /> <feFlood flood-color="#FF0000" result=" ...

You have exceeded the maximum number of Facebook application requests allowed (#4)

My goal is to create a dynamic "social wall" on a website by pulling posts from a specific Facebook page using the Facebook API. Instead of utilizing any Facebook SDK, I am making cURL calls with the URLs directly. To fetch the posts, I rely on Javascript ...

Browser stores cached data for images even after they have been removed and then re-added

Our team is currently working on a web application that relies solely on AJAX and Javascript for its interface. One challenge we have encountered involves dynamic images with cache expiration times set to access time plus 15 minutes. Typically, when these ...

Learn how to utilize ng2-file-upload in Angular for uploading .ply files effortlessly!

I'm currently working on uploading various files using ng2-file-upload. I've been successful in uploading different file types like png and jpg, but I'm facing an issue with the .ply file extension. Can someone guide me on how to upload a fi ...

Dependable Timeout Functionality in JavaScript

We are currently developing an AngularJS application that presents users with questions and keeps track of the number of correct answers within a strict 20-minute time limit. However, there are some challenging requirements we need to consider: Accuracy C ...

Transforming functions with dependencies into asynchronous operations with the help of promises

Can I convert both of my functions into asynchronous functions, even though one function relies on the other? Is it feasible for function b to execute only after function a? ...

Exchange CSS Styles with a Single Click Event in JavaScript

Struggling with getting a click event to function properly on my webpage. I have a Div labeled 'icon' with the class 'lock', and I aim to allow users to click on the background image of this Div to switch its class from 'lock' ...

Display the jQuery validation message in the final td cell of the table

JavaScript Animation Library rules:{ gender: { required: true }, }, messages:{ gender: { required: "Please indicate your gender" }, }, errorPlacement: function (error, element) { if (element.attr("type") == "radio") { ...

State changes are not being properly reflected in the function within Next.Js

I am currently working on a functional component that displays an array of products. The products are received as props and the component utilizes the useEffect and useState hooks to manage its state. One of the functionalities I am trying to implement is ...

How to efficiently insert multiple documents into MongoDB using JavaScript

I'm currently working on inserting data into a MongoDB collection. I have a loop set up where I am receiving sample data in each iteration as shown below: 13:24:24:007,Peter,male,3720,yes 13:24:24:007,John,female,1520,yes 13:24:24:023,John,female,972 ...

NgModel in Angular Datapicker does not successfully transmit value

My page features a form that functions as a filter search, with one of the fields being a date field. I have configured the Angular UI datepicker plugin (https://github.com/angular-ui/ui-date) and the calendar pops up when I focus on the date field. Howe ...

Encounter TypeScript error when using getFirebaseAdmin from next-firebase-auth

I am currently utilizing a package called next-firebase-auth. I am encountering an issue when calling getFirebaseAdmin from next-firebase-auth and attempting to use it, specifically when using db as a reference in doc(db). The error message received is: ...

looking to showcase the highest 'levelNumber' of elements within an array

arr1 = [ { "levelNumber": "2", "name": "abc", }, { "levelNumber": "3", "name": "abc" }, { "levelNumber": "3", "name": &quo ...

I'm having trouble viewing the unique Google Map design on my application

I have recently customized Google maps following the guidelines in this documentation: https://developers.google.com/maps/documentation/javascript/styling For styling, I utilized the Cloud tool and opted for the available template instead of using JSON st ...

Converting Javascript Array to PHP Array: A Step-by-Step Guide

For my web application, I am utilizing PHP and MySql. When inserting a string into Mysql, it is formatted as a JavaScript Array ["0","1","2","3","4","5","6"] After retrieving the value from the database, it is saved in a PHP Variable $dow I am now looki ...