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

Exploring the varying treatment of the noscript tag across different web browsers

I've been searching everywhere, but I can't find any information on this topic. What I really want to understand is what browsers do with the content inside a noscript tag when JavaScript is enabled. Let's consider an example: According t ...

How can I dynamically retrieve the width of an image in React as the screen size changes?

I have successfully implemented an image hover effect on my website. When I hover over a certain text, an image appears. The image is responsive, but I am facing an issue where I want the width of the text to be equal to the width of the image. When I resi ...

When a specific function is called, the DayPickerRangeController in the airbnb/react-dates library will update the

Is it possible to dynamically set the visible month in DayPickerRangeController after the component has been rendered? I have a 'handleMonthChange' function that I want to use to change the visible month, but setting 'initialVisible' mo ...

choosing a suggestion by onkeypress (jquery-ajax) utilizing the arrow keys pointed up and down

I have implemented an auto-suggest box with a fancy apple style suggestion box. Everything is functioning well, but I would like to enable users to select a value from the suggestion box using the up or down arrow keys. How can I implement this functionali ...

Getting the Tweets of a Twitter-validated user using node.js

I'm struggling with extracting Tweets from a verified user and could use some assistance. I know it's a broad question, but here's the situation: https://github.com/ttezel/twit provides a way to access tweets from any Twitter account. Howev ...

Error parsing data in Ajax POST request

I'm currently working on developing a web chat room. I encountered an issue when sending a POST request to the server using the following code snippet: var line_count = 0; $.ajax({ type: 'POST', url: '../scripts/engine.php&apo ...

Trouble transferring $rootScope.currentUser between AngularJS profile and settings page

I am in the process of setting up a site using Angular, Express, Node, and Passport. Currently, I am configuring Angular to monitor the $rootScope.currentUser variable with the following code: app.run(function ($rootScope, $location, Auth) { // Watch ...

The combination of jquery, ajax, and php resulted in a successful GET request to http://www.site.dk/?userid=admin&pass=admin, returning a

Greetings! I am currently working on two separate Wordpress websites with different domains and I am attempting to pass some values from one site to the other using ajax. However, I am facing an issue. Even though the URL works fine when directly entered ...

Meteor chat platform now offers the option to create multiple chat rooms

I've been working on an application that features multiple chat rooms. Currently, one of the rooms is functional in terms of sending and receiving messages. However, when I navigate to a different room and try to send a message, the message doesn&apos ...

I'm stumped trying to understand why I keep getting this syntax error. Any thoughts on how to fix it?

Our team is currently working on creating a dynamic SELECT box with autocomplete functionality, inspired by the Standard Select found at this link: We encountered an issue where the SELECT box was not populating as expected. After further investigation, ...

Encountering a pair of errors while working with Node.js and Express

(Apologies for the vague title) I have been developing a project using Firebase and Express, but I am encountering some issues. src/index.js import { initializeApp } from "firebase/app"; import { doc, getFirestore } from "firebase/firesto ...

Unusual shadow cast by the box's silhouette

I am currently facing an issue with a box and its shadow. When I close the box, a different shadow lingers behind. I have tried troubleshooting this problem but cannot pinpoint the source. I have included the relevant code files in the specified folders. I ...

Comparing Redux with passing state down to components as props from the top level of the application

With limited experience in react-redux, I am currently working on a smaller web-based application intended for around 100 users. At this time, I have opted not to use redux due to concerns about its complexity for such a small project. Instead, I have been ...

Determining the width of an element in Chrome using jQuery

Before adding an element to the body, I require its width. The code below functions correctly in Firefox, however it does not work properly in Google Chrome. <style> .testDiv { width:150px; height:100px; } </style> <script> var di ...

JavaScript code is failing to render data properly within HTML documents

I am facing an issue while trying to display data extracted from JSON in HTML. Despite my efforts, the data is not showing up on the webpage. I am unsure about what might be causing this error. Any assistance in resolving this matter would be greatly appre ...

I'm attempting to create a button that changes to a bold red color when the condition is met

I am currently working on developing web applications using the Pixabay API. My goal is to allow users to mark an image as a favorite and have the heart icon change color to red accordingly. However, I seem to be facing issues with this functionality. To ...

Developing with Angular 1.4.8 and JavaScript involves the process of building a constructor function to inherit properties into a third object

DEVELOPER TOOLS Using Angular 1.4.8 and lodash QUERY: REVISIT To clarify my query: Create an object (articles) Apply a constructor Import the properties of a third object, but place it in proto folder to prevent cluttering the root with a large colle ...

Using Node JS, how to pass a variable length array to a function?

Is there a way to dynamically call an addon function with varying argument lengths? I capture user input in a variable like this: Uinput = [5,3,2]; Now, I want to pass these numbers as arguments to my addon function like this: addon.myaddon(5,3,2); I n ...

Adjusting font sizes in JavaScript causes the text to resize

Within my HTML pages, I am adjusting the font size using JavaScript code like this: "document.body.style.fontSize = 100/50/20" However, whenever the font size changes, the text content on the page moves up or down accordingly. This can be disorienting for ...

How to toggle a boolean variable in AngularJS when transitioning between states

Just getting started with AngularJS and trying to figure out how to tackle this issue. I have set up the following route: name: "Tracker", url: "/tracker/:period", and I have 3 distinct states for which I've created 3 separate functions to facilit ...