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

Evolution of ReactJS state over time

When working with React, I wanted to increment a state variable called progressValue by 0.1 every 500 ms until it reaches 100. Here's what I initially tried: const [progressValue, setProgressValue] = React.useState<number>(0) const tick ...

Encountering a top-level-await issue while utilizing the NextJS API

Currently, I am in the process of creating an API using NextJS and MongoDB. To start off, I have set up some basic code at the beginning of the API file: const { db } = await connectToDatabase(); const scheduled = db.collection('scheduled'); Fol ...

Manipulating values in JavaScript using an onclick event in PHP

I am looking to remove the "http" from the URL part of an input link before sending the data. This is my input code that looks like this when clicked: <input style="outline: none;" type="button" onclick="formatText ('link:url');" class="btn ...

React - Obtain User Login Details and Verify

I am working on a React project that includes a Login Form. The code has been organized into small components for reusability, but I am unsure of how to retrieve and validate user credentials (username and password). Is there a method available to validate ...

How to Troubleshoot VueJS Component Render Issues After Importing/Calling Components

In one of my projects, I successfully implemented a file uploader component using import and component statements. import fileUploader from '../common/FileUploader.vue'; Vue.component('file-uploader', fileUploader); This implementation ...

When working with ASP.NET MVC, I encountered an unexpected issue where a JSON response was sending me a file instead of

After receiving JSON data, I observed that instead of updating the jQuery accordion, it prompts to save or open a file. Below is my code and controller setup. I have integrated a jQuery modal dialog for editing employee details using a partial view. When c ...

Navigating using Javascript library in Angular 2 framework

I am currently utilizing Parse, an external JS library, within Angular JS 2. Nevertheless, I am encountering issues when attempting to call the function gotoMain() from within a callback function of Parse. It appears that certain elements are not being l ...

What is the best way to define the scope of an HTTP request within my application?

I need assistance with setting the scope for an http request in my Ionic App. Our Backend is built with Node.JS using the Hapi Framework. Since I primarily work on the frontend, I lack knowledge of server-side operations. Currently, I am able to successfu ...

Avoid updating the input from ng-model while it is being edited

There are times when my model.field can be altered by both user input into an input field and by other functions running in the background. However, I want to handle situations where changes made by the user take precedence over modifications made by those ...

initiating AngularJS ng-model pipeline on blur event

My $parser function restricts the number of characters a user can enter: var maxLength = attrs['limit'] ? parseInt(attrs['limit']) : 11; function fromUser(inputText) { if (inputText) { if (inputText.length > max ...

What is an effective method for coordinating JQuery animations simultaneously?

My current understanding of $("#someElement").animate() is that it will run asynchronously in relation to other JavaScript statements. For example: $("#anotherElement").css("display", "none"); $("#someElement").animate(); //The CSS display may change a ...

Is the element loaded but not appearing on screen?

I am facing an issue when using ajax to send data to a PHP server and displaying it in the view. Even though the data loads successfully (checked in console), it does not display in the view. Can someone please help me resolve this? Here is my code : Vie ...

Introducing a pause in the function while rendering objects

After inserting setInterval into the code, it is causing all lasers to be delayed by one second. I am looking to have them fired in this order: - initially fire laser1 and laser2. - then take a 1-second break before firing another set of lasers, a ...

Using Vue JS to display information conditionally within a single component

I currently have a component that dynamically displays the data from an array of objects. However, I want the component to display only one object based on a specific condition. Is it possible to show either one object or another depending on the value o ...

Having trouble implementing Bootstrap Progress Bar with AJAX in webpy

I am currently working on a web application using webpy and dealing with a Bootstrap progress bar in the template HTML file. To update this progress bar dynamically, I aim to utilize jQuery AJAX calls to fetch data from the server. In order to achieve thi ...

How can I create a route using associations for /users/me in Sails.js?

My primary model is called Accounts. Additionally, I have several Has Many models such as Notifications and Friends Within my file named main.js, I would prefer to execute commands like: socket.get('/users/me/notifications'); instead of: soc ...

What causes the jQuery mouseenter events to be activated in a random sequence?

I currently have a setup of 3 nested divs, resembling the concept of a Matryoshka doll. Each div has a mouseenter event function bound to it. When moving the mouse slowly from the bottom and entering layer three, the events occur in the following sequence ...

Move to Fieldset Upon Link Click

Here's an example of what I have implemented so far here It's evident that this is not fully functional due to the PHP and jQuery integration. This demo is just a showcase of my progress. I am looking to create a functionality where clicking on ...

Tips for enabling selection of list items in an input tag

Below is the code I have written to create an InputFilter. MyFilter = function(args) { var dataUrl = args.url; var divID = args.divID; var div = document.getElementById(divID); var myTable = '<input type="text" id="myInput" on ...

What is the proper way to link an image in a nuxt project?

I am working on a modal in the app.html file of my Nuxt project that prompts Internet Explorer users to switch to another browser. The modal includes links to three different browsers for download. Although the modal is displaying correctly, I keep encount ...