A new marker has been created on the Ajax Google Map, however, the old marker is still displaying as

Hey, I'm currently working on retrieving marker latitudes and longitudes using Ajax. I am receiving Ajax data every second and successfully creating markers within a specific radius. However, I'm running into an issue with updating marker positions where new markers are created while the old ones still remain visible. Can someone please assist me in updating the markers fetched from Ajax and removing any extras?


var map = null;
var geocoder = null;
var markers = {};
var infoWindow = null;
var minZoomLevel = 16;

jQuery('#search').click(function() {
    var address = jQuery('#address').val() || 'India';
    if (map === null)
        initializeMap();
    searchAddress(address);
});

// Initialize the Map
function initializeMap() {
    // Map Options
    var mapOptions = {
        zoom: minZoomLevel,
        draggable: true,
        disableDefaultUI: true,
        scrollwheel: true,
        disableDoubleClickZoom: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    
    // Create a new Google Map
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);     
  
    // Check for Geolocation Support
    if (navigator.geolocation) {
         navigator.geolocation.getCurrentPosition(function (position) {
             initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
             map.setCenter(initialLocation);
            
            // Limit the zoom level
            google.maps.event.addListener(map, 'zoom_changed', function () {
                if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
            });
         });
     }
     
    google.maps.event.addListener(map, "idle", function(event) {
        searchStoresBounds();
    });
    
    geocoder = new google.maps.Geocoder();
    infoWindow = new google.maps.InfoWindow();
}

// Search Address Function
function searchAddress(address) {
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
            var latlng = results[0].geometry.location;
            map.setCenter(latlng);
            
            // Limit the zoom level
            google.maps.event.addListener(map, 'zoom_changed', function () {
                if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
            });
            
            searchStoresBounds();

        } else {
            alert('Geocode was failed: ' + status);
        }
    });
}

// Perform a Store Search within Bounds at regular intervals
setInterval(function searchStoresBounds() {
    var bounds = map.getCenter().toUrlValue();
    var url = './store.php';
    var parameter = { bounds: bounds };
    
    // Fetch Data using Ajax
    jQuery.ajax({
        url: url,
        data: parameter,
        dataType: 'json',
        success: showStores
    });
}, 1000);

// Display Stores on the Map
function showStores(data, status, xhr) {
    if (data['status'] != 'OK')
        return;
        
    var id;

    // Add Markers for New Stores
    for (id in data['data']) {
        if (markers[id] === undefined)
           createMarker(id, data['data'][id]);
    }

    var b = map.getBounds();
    
    // Remove Markers outside the bounds
    for (id in markers) {
        if (! b.contains(markers[id].getPosition())) {
            markers[id].setMap(null);
            delete markers[id];
        } else {
            createMarker(id, data['data'][id]);
        }
    }
}

// Create New Marker
function createMarker(id, store) {
    var latlng = new google.maps.LatLng(
                parseFloat(store['lat']),
                parseFloat(store['lng'])
            );
    
    var html = "<b>" + store['address'] + "</b>";
   
   // Additional Marker Configuration
   
       var marker = new google.maps.Marker({
            map: map,
            position: latlng,
            icon: icon,

        });
    google.maps.event.addListener(marker, 'click', function() {
            infoWindow.setContent(html);
            infoWindow.open(map, marker);
        });
    markers[id] = marker;
}

Answer №1

The issue you are experiencing is related to this specific section of code:

var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        icon: icon,

    });

Each time data is retrieved from ajax, a new marker is created.

To resolve this, include the following declaration at the beginning of your js file:

var marker;

Update the marker creation like this:

if(marker)
{
   marker.setMap(null);
}
marker = new google.maps.Marker({
        map: map,
        position: latlng,
        icon: icon,
   });

This modification ensures that before a new marker is added, the previous one is removed from the map. The condition `if(marker)` is essential to avoid errors when attempting to remove a non-existent marker on the first execution.

Additional Note :

If you have multiple markers, it's crucial to maintain an array of markers and clear them before adding new ones to the map.

In your code, declare a marker array at the top of the page like this:

var markerArray = new Array();

Prior to adding new markers, clear the existing markers using:

for(var i = 0; i<markerArray.length; i++)
{
   markerArray[i].setMap(null);
}
markerArray = new Array()

After this process, continue with your current code for creating markers:

var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        icon: icon,
   });

markerArray.push(marker);

Ensure to add each marker to the markerArray for proper maintenance in subsequent executions of your code.

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

Building with bricks and mortar does not involve organizing visual content

I'm currently trying to organize some fairly large images using masonry, but the code below doesn't seem to be working. I'm using node.js with express and have installed the masonryjs package in an attempt to make it work, but that approach ...

Implementing Prototype and Ajax for your updates

Currently, I am utilizing the power of Ajax along with Prototype. In my script, there's a need to refresh the data within a div. The designated div: <div id="update"> 1. Content_1 </div> Snippet from my code: Element.update( ...

Creating a feature in Angular JS that allows for each item in a list to be toggled individually

Looking for a more efficient way to toggle individual buttons without updating all at once? Check out this basic example where each button toggles independently by using ng-click="selected = !selected". Instead of updating all buttons at once, you can achi ...

Is there a way for me to extract and showcase the initial 10 items bearing a particular class name from a different html document on my homepage?

I am looking to extract a list of movies from an HTML file titled "movies.html". The structure of the file is as follows: <div class="movie">Content 1</div> <div class="movie">Content 2</div> <div class=" ...

The Jquery code encountered an issue where it was unable to access the property 'length' of an undefined

My goal is to submit a form using jQuery and AJAX, which includes file upload functionality. The challenge I'm facing is that the forms are dynamically created, so I need to identify which form was clicked and retrieve its input values. $(document).r ...

How can I ensure my AngularJS Controller variable is accessible across all page contexts?

Working with AngularJS, I have a view controller where I initialize a variable called recipesData. Here is the code for the controller: (function() { 'use strict'; angular .module('myApp') .controller('Coo ...

using java to invoke a server-side function within a mapReduce operation in mongodb

i have saved two functions in the "system.js" collection under the names "mapfun" and "reducefun" and now i am attempting to invoke these functions from Java. I am trying to utilize MapReduceCommand for this purpose but encountering difficulties in calling ...

Using ng-if in AngularJS to compare two objects

I am transferring between controllers with different formations, and I am attempting to use "ng if" to compare the ids, but it is not functioning as expected. Below is the code snippet: var postsApi = 'http://mywebsite.com/wp-json/posts?filter[p ...

What is the method for accessing the req, res objects within the callback functions?

One of my preferences is to access the req, res, next objects outside of the middleware function. For instance, in a sample middleware file called sample.js: var app = express(); .... ..... .... var updateUserInput = { init:function(){ get_data ...

Loading a different webpage seamlessly without having to reload the current one

Here is a snippet of my code in okay.html: {% extends "sch/base.html" %} {% load staticfiles %} {% block content %} <div class="row" id="ada"> <form action="" method="post> {% csrf_token %} <div align="center" class="cont ...

Implement necessary validation for the country code selection on the dropdown menu using the intl-tel-input jQuery plugin

Check out the intl-tel-input plugin here Currently, I am utilizing this plugin and attempting to implement required validation on the country code drop-down. However, the plugin seems to be restricting me from achieving this. I have made several attempts ...

Setting up NextJS on Vercel for website deployment can encounter a common error known as ENOENT Error, which is caused by the absence of a specific file or

Everything works perfectly on my local machine: import fs from 'fs' import path from 'path' export default function createNewDirectory (tokenSignature: string) { const directoryPath = path.join(process.cwd(), 'notes', to ...

Switch the ng-bind-html option

Dealing with a string in my scope, I must determine whether I want the HTML escaped or not. A boolean value helps to decide if the HTML should be escaped or left as is. Snippet Check out some of my code examples below: $scope.result = "<b>foo</ ...

JavaScript - utilize regular expressions to check if the argument starts with a forward slash

Currently, I am utilizing nodejs for API testing purposes. To properly test the logic within this if statement, I am in search of a string that aligns with this specific regular expression. if (arg.match(/^\/.*/)) { // ... } Would anyone be able ...

Tips for stopping a Node.js for loop if it runs for more than 20 seconds

Imagine a situation where I have a for loop performing some actions, and I want to terminate the loop if it takes longer than 20 seconds to complete. async function mainFunc(){ for (let step = 0; step < 5; step++) { // Executes a complex op ...

When making xmlhttp requests, IE9 will prioritize loading from the cache rather than from the server when the data is available

During my local development process, I've been utilizing this AJAX code: function getChart(num,ld,margin,idr) { idr = typeof(idr) != 'undefined' ? idr : 0; $(ld).style.display="inline-block"; if (window.XMLHttpRequest) { ...

existing event handler in JavaScript has already been registered on a particular plugin

Apologies for the confusing title, will make changes accordingly.. Currently, I am utilizing the Twitter Bootstrap Wizard to manage database operations. My goal is to find a way to activate the onTabShow() function by simply clicking a button. The onTabSh ...

Troubleshooting Issue with Eloquent Laravel 8 Ajax Request with Inner Join Query

I have encountered an issue while attempting to retrieve data from two tables using inner join in Laravel 8 and display it as a datatable on the front end through Ajax. However, my ajax call is resulting in an internal server error. Below is my controller ...

Exploring the power of PHP through a while loop for AJAX requests

I've implemented this ajax code: $.ajax({ type: "GET", url: '../connect.php', data: "OrB=" + ajaxsend+"&&IOr="+i, success: function(data ...

I'm experimenting with crafting a new color scheme using MUI, which will dynamically alter the background color of my card based on the API

I am attempting to create a function that will change the colors based on the type of Pokemon. However, I'm not sure how to go about it. Any suggestions or ideas!? Check out where I'm brainstorming this logic [This is where the color palette sh ...