Use the Google Maps API to dynamically add a marker via AJAX once the map has been initialized

Although I have come across similar questions with related titles, none of the answers quite fit my needs.

Here is the problem I am facing:

I'm working on printing a map that contains multiple markers generated from a database. Below the map, there are checkboxes that allow me to filter the markers displayed on the map.

Initially, when I load the map, everything is correctly filtered based on the default settings of the checkboxes. However, I am unsure how to add or remove markers from the map once it has been initialized. Do I need to reload the map, or is there something else I should be doing?

Below you can find the relevant code:

<form>
<input class="test" type="checkbox" name="type" value="1" onclick="test()" checked/>1<br/>
<input class="test"type="checkbox" name="type" value="2" onclick="test()" checked/>2<br/>
<input class="test"type="checkbox" name="type" value="3" onclick="test()" checked/>3<br/>
<input class="test"type="checkbox" name="type" value="4" onclick="test()" checked/>4<br/>

<script>
var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get().join('-');

function fetchPlace(filterType){

$.ajax({
    url: "ajaxmap.php?type=" + filterType,
    type: 'GET',
    dataType: 'json',
    success: function(data) {

     // Loop through our array of markers and place each one on the map  
        for (i = 0; i < data.marker.length; i++) {
            var myLatlng = new google.maps.LatLng(data.marker[i].log, data.marker[i].lat);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: 'Hello World!'
            });
        }
    },
    error: function(){
        /// handle errors
    },
    async: true
});
};

function test (){
    var checkedValues = $('input:checkbox:checked').map(function() {
        return this.value;
    }).get().join('-');
    fetchPlace(checkedValues);
};

fetchPlace(checkedValues);

Thank you in advance for any assistance you can offer.

Loneept

Answer №1

My solution involved working with 2 arrays of coordinates that simulate what you'd receive in an AJAX success callback.

The array named markers is utilized to categorize markers based on their filter type. Inside the function addMarkers, I initialize an array for each filter type like so:

markers[filterType] = new Array()
.

This approach allows for easy identification and toggling of markers belonging to different types.

You may need to customize this setup to suit your specific requirements (e.g., using checkboxes instead of buttons) or optimize the loading process based on your needs. Nonetheless, the overall concept should be clear.

var map;
var markers = new Array();

var coords_1 = [
    new google.maps.LatLng(60.32522, 19.07002),
    new google.maps.LatLng(60.45522, 19.12002),
    new google.maps.LatLng(60.86522, 19.35002),
    new google.maps.LatLng(60.77522, 19.88002),
    new google.maps.LatLng(60.36344, 19.36346),
    new google.maps.LatLng(60.56562, 19.33002)];

var coords_2 = [
    new google.maps.LatLng(59.32522, 18.07002),
    new google.maps.LatLng(59.45522, 18.12002),
    new google.maps.LatLng(59.86522, 18.35002),
    new google.maps.LatLng(59.77522, 18.88002),
    new google.maps.LatLng(59.36344, 18.36346),
    new google.maps.LatLng(59.56562, 18.33002)];
    
// Other functions and initialization steps omitted for brevity

initialize();

Check out the JSFiddle demo for a visual representation.

In your scenario, a similar logic could be applied as demonstrated below:

// Marker array declaration at script start
var markers = new Array(); 

...

// Iterating through marker data & placing them on the map  

markers[filtreType] = new Array();

for (i = 0; i < data.marker.length; i++) {
    var myLatlng = new google.maps.LatLng(data.marker[i].log, data.marker[i].lat);
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: 'Hello World!'
    });

    markers[filtreType].push(marker);
}

Edit:

An alternative method involves assigning the filter type directly to each marker and storing all markers in a single array for easier management and identification.

// Marker array declaration at script start
var markers = new Array(); 

...

// Looping through marker data & displaying them on the map
for (i = 0; i < data.marker.length; i++) {
    var myLatlng = new google.maps.LatLng(data.marker[i].log, data.marker[i].lat);
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: 'Hello World!',
        filterType: filtreType
    });

    markers.push(marker);
}

If you intend to remove markers of a specific filter type, the following function can be used:

function removeMarkers(filterType) {

    for (var i = 0; i < markers.length; i++) {

        if (marker.filterType === filterType) {

            markers[i].setMap(null);
        }
    }
}

Note: Ensure consistency between variables filterType and filtreType to prevent confusion. It's recommended to use filterType consistently throughout your codebase.

Answer №2

To effectively manage markers in Google Maps, it's important to utilize an array to store references to them. This way, you can easily loop through all the markers and modify their properties as needed. For example, you can set the "map" property to null or remove the markers from the array altogether.

Here is a sample code snippet demonstrating how you can implement this:

function fetchPlace(filtreType){

  var markers = [];

    $.ajax({
        url:    "ajaxmap.php?type=" + filtreType,
        type : 'GET',
        dataType: 'json',
        success : function(data) {

         // Iterate through the marker data and place each one on the map  
            for( i = 0; i < data.marker.length; i++ ) {
                var myLatlng = new google.maps.LatLng(data.marker[i].log,data.marker[i].lat);
                var marker = new google.maps.Marker({
                      position: myLatlng,
                      map: map,
                      title: 'Hello World!'
                  }); /* <----- MARKER CREATED AND PLACED ON THE MAP HERE */
               markers.push(marker); /* <----- STORING MARKERS IN ARRAY FOR FUTURE ACCESS */

            }
        }
        ,
        error: function(){
            /// Handle errors here
        },
        async : true
    });



}

When calling fetchPlace multiple times, the existing markers will be cleared, and new ones will be added based on the retrieved data.

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

Vanishing Tooltip following an implementation of the backdrop-filter

I'm having an issue with the blur effect on my background image. Although it works well, my tooltips also end up being blurred behind the divs: https://i.stack.imgur.com/BMdh4.png Is there a way to ensure that my tooltips stay on top of the subseque ...

The Contact.php page has the ability to send emails, however, the content of the

I have recently added a contact form to my website using a template. Although I am able to send and receive email messages successfully, I am facing an issue where the actual message content entered by users is not being received in my Inbox. Here is a sc ...

Jquery Ajax Request

My goal is to create an Ajax call with the following specifications: $.ajax({ type: "GET", dataType: "json", contentType: "application/json", username: "user123", password: "admin123", url: "http://localhos ...

Strange error message: Attempting to set properties of null (changing 'innerHTML')

I have been working on a project where I am creating a website that retrieves data from a specified URL, displays it on the front end, and performs certain functionalities with that data (although this part is not yet implemented). However, I have encounte ...

Unable to execute internal functional tests due to this error: [POST http://localhost:4444/wd/hub/session] unable to connect - ECONNREFUSED

Currently working with node 0.12 and intern 3 in order to execute functional tests, but encountering the following error: SUITE ERROR Error: [POST http://localhost:4444/wd/hub/session] connect ECONNREFUSED at Server.createSession <node_m ...

Optimal approach for vertically aligning elements in CSS

I'm looking to arrange my header ('Sail away today with Starboard Rentals.') and link buttons on top of each other. I want the navigation buttons to be positioned below the h1 on the lower half of the 'home-jumbo' div. What's ...

Modifying the value of a property in one model will also result in the modification of the same

As a beginner with Vue, I am looking to allow users to add specific social media links to the page and customize properties like text. There are two objects in my data - models and defaults. The defaults object contains selectable options for social media ...

Create a new array of objects by extracting specific properties from an existing array of objects

Consider the input array below: const initialArray = [{name: 'john', age: 12, height: 178, likes: 'music'}, {name: 'mike', age: 22, height: 181, likes: 'sport'}, {name: &ap ...

The website flickers in and out as it loads

My site keeps flashing whenever it loads. Despite trying the solutions recommended in this stackoverflow post, I have had no success. Every page on my website loads a nav.html file using this code: $.get("nav.html", function(data){     $("#nav-placeho ...

Having trouble with Javascript/ajax/php: data is successfully sent from server to client, but client to server communication is not working as

Apologies for the duplicate post (Admins, kindly remove the other one!). I've been receiving great assistance from you all and was hoping to seek your help once again with the following question: I am currently working on implementing AJAX by allowin ...

Executing a complex xpath using Java Script Executor in Selenium WebDriver

When working with a large grid and trying to find an element using XPath, I encountered some difficulties. The XPath used was: By.xpath("//div[contains(text(),'" +EnteredCompetitionName+ "')]/preceding- sibling::div[contains(concat(' &apo ...

The method .depth() does not exist within this context

When I attempted to execute this code using npm start in the terminal //index.js const api = require('./api'); console.log('Starting monitoring!'); setInterval(async () => { //console.log(await api.time()); console.log(await ...

Having trouble sending a function as a prop to a child component in React

Something odd is happening, I'm confident that the syntax is correct, but an error keeps popping up: Error: chooseMessage is not a function // MAIN COMPONENT import React, { useState } from 'react' export default function LayoutMain(prop ...

Joining arguments beyond argv[2] in a Node.js application

Recently, I received a suggestion from Mykola Borysyuk to use node-optimist. However, the author mentioned that it's deprecated and recommended using Minimist. Even after going through the information, I have a basic understanding. Can someone provid ...

Combining the powers of Nextjs and Vue

Currently utilizing Vue.js, I am now looking to leverage the Next.js framework for its SEO capabilities, server-side rendering features, and other advantages. While I do have some experience with React, my primary focus is on mastering Vue.js. Is it poss ...

Loop through the received ajax POST data using a foreach statement and handle values that are separated by commas

Any help with this issue would be greatly appreciated as I am struggling to find a solution on my own. Currently, I am working on implementing a filtering system for a job board using ajax, jquery, and php. When I select multiple checkboxes, the data bein ...

The hierarchy of script loading in Angular applications

After years of working with MVC, I recently delved into Angular. Although I am well-versed in JavaScript and HTML, I'm still a beginner in the world of Angular. I spent hours troubleshooting my app only to realize that the problem was elusive. The a ...

Turning a text into a JSON data structure

How can I make JavaScript recognize a string as JSON? I have a function that only works when passed a JSON object. If I pass a string with the same format as JSON, it doesn't work. I want to find a way for the function to treat the string as JSON, ev ...

Challenges with TypeScript build in DevOps related to Material UI Box Component

Currently, I am facing an issue while trying to build a front end React Typescript application using Material ui in my build pipeline on Azure DevOps. The problem seems to be related to the code for the Material ui library. Despite successfully building th ...

Navigate a JSON object using JavaScript

As I continue to juggle learning code with my job, I am diving into the world of creating charts using AMcharts. My goal is to generate multiple data sets based on orientation and potentially expand further in the future. In the JSON snippet below, you can ...