Release a single marker each time

Struggling with the Google Maps API v3 to drop markers one at a time on my map? I want it to work like the Google Demo, but all markers are dropping at the same time. Here's my code:

var map;
var markers = [];

function initialize() { 
    var latlng = new google.maps.LatLng(52.520816, 13.410186);

    var options = {
        zoom: 5,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map-canvas"), options);
}

initialize();

function loadMarkers() {  

    $.ajax({
       url: 'js/poi.php',
       type: 'GET',
       dataType : "json",
       success: function (data) {

            var latlngbounds = new google.maps.LatLngBounds();      

            // Loop through data and drop a marker for each point
            $.each(data, function(index, point) {

                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(point.Lat, point.Lng),
                    animation: google.maps.Animation.DROP,
                    icon: 'img/marker.png'

                });

                markers.push(marker);
                latlngbounds.extend(marker.position);

            });

            // Cluster and fit bounds
            var markerCluster = new MarkerClusterer(map, markers);
            map.fitBounds(latlngbounds);

        }

    });
}

loadMarkers();

I attempted to use a Timeout on each marker, but it seems that loadMarkers(); is causing them to drop simultaneously.

setTimeout(function() {

    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(point.Lat, point.Lng),
        animation: google.maps.Animation.DROP,
        icon: 'img/marker.png'

    });

}, point.Id * 200);

Any suggestions on how to resolve this issue?

EDIT: The poi.php file lists all points from my Table and outputs them in the following format:

[
{"Id":"1","Lat":"52.511467","Lgn":"13.447179"},
{"Id":"2","Lat":"52.549061","Lgn":"13.422975"},
{"Id":"3","Lat":"52.497622","Lgn":"13.396110"},
{"Id":"4","Lat":"52.517683","Lgn":"13.394393"}
]

Answer №1

  1. place the markers into the clusterer as they are introduced to the map
  2. modify the bounds to display the markers as they are included
  3. corrected a typo in the JSON (uncertain if it impacts anything)
function initialize() {
    var latlng = new google.maps.LatLng(52.520816, 13.410186);

    var options = {
        zoom: 5,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map-canvas"), options);
    loadMarkers();
}

function loadMarkers() {
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/echo/json/',
        data: {
            json: JSON.stringify(jsonData)
        },
        delay: 3,
        success: function (data) {
            var markerCluster = new MarkerClusterer(map, markers);
            var latlngbounds = new google.maps.LatLngBounds();
            $.each(data, function (index, point) {
                    setTimeout(function() {
                      var marker = new google.maps.Marker({
                        position: new google.maps.LatLng(point.Lat, point.Lng),
                        animation: google.maps.Animation.DROP,
                        map: map /* don't have your custom marker
                        icon: 'img/marker.png'*/
                      });
                      markerCluster.addMarker(marker);
                      markers.push(marker);
                      // adjust the bounds to show all the markers
                      latlngbounds.extend(marker.getPosition());
                      map.fitBounds(latlngbounds);
                    }, point.Id * 200);
            });
        }
    });
}

view working fiddle here

Answer №2

To begin, create a marker using the following values:

   var marker = new google.maps.Marker({
            position: new google.maps.LatLng(point.Lat, point.Lng),
            map: null,
            visible:false
    });

Define a variable to track the timeout counter and reset it whenever the map's zoom level changes (which triggers re-clustering)

google.maps.event.addListener(map,'zoom_changed',function(){
  this.set('counter',0);
})

Listen for the map_changed event of the markers to implement the animation when a previously clustered marker is removed from a cluster

google.maps.event.addListener(marker,'map_changed',function(){
      var marker=this,map=this.getMap();
      //the marker has been clustered
      if(!this.getMap()){     
        this.setValues({visible:false});
      }
      //the marker is not a part of a cluster
      else{
        //the marker was previously clustered, so set it as visible with an animation after a delay
        if(!this.getVisible()){
            var counter=this.getMap().get('counter')+1;
            //update the counter value
            this.getMap().set('counter',counter);
            setTimeout(function(){marker.setValues({animation:google.maps.Animation.DROP,
                                                    visible:true});},
                       200*counter)
        }
      }


});

View the outcome here: http://jsfiddle.net/doktormolle/9jaLqpfd/

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

Execute asynchronous JavaScript request

When a user types something into the input id=2, an ajax function triggers. Here is the HTML: <input id="2" type="text" onkeyup="posttitulo(this.value)" /> And here is the SCRIPT: function posttitulo(value){ $.post("getdata/posttitulo.php",{p ...

What are some strategies for boosting the efficiency of a recursive element in React?

Within my React Native Expo project, I've implemented a recursive comment component to facilitate the rendering of nested comment threads. However, as the number of comments grows, performance begins to suffer, resulting in a less-than-ideal user exp ...

Which is Better for Creating DropDown Menus: CSS or JavaScript?

Starting a new project that involves dropdown menus with categories and subcategories within them. I'm curious about the advantages of using CSS3 only menus compared to traditional JavaScript ones. There are several jQuery menu options available as we ...

Guide on sending a JSONArray from ajax to the controller

Currently working with Spring MVC in Java, I am faced with an issue where I am attempting to pass a List from JavaScript to the controller as a JSONArray. However, upon reaching the controller, it is either showing up as an empty array or null. Would grea ...

I have a dynamic blog site that is generated on the fly using Ajax, making the content unsearchable

I have a blog website that is created dynamically using Ajax (XMLHttpRequest) and the HTML History API. One issue I am facing is that my content is not searchable by search engines like Googlebot. I know that Google is now able to analyze such sites, but w ...

Transfer data from distinct arrays to separate variables

I have 2 arrays structured like this: let dataA = [{"id": "a1", "name": "Alpha"}, {"id": "a2", "name": "Beta"}, {"id": "a3", "name": "Gamma&quo ...

What is the reason for the presence of additional mandatory dependencies in the package-lock.json file?

The recent release of React includes breaking changes to the TypeScript typings, causing packages that require "@types/react" with a wildcard version to automatically target this new version and break my project. Initially, I wanted to reach out to projec ...

Preventing Duplicate Entries in Angular Data Posting

I am currently trying to submit a form to a PHP page that will then return a table of data. The process works perfectly fine if I do not include any parameters in the post request. However, as soon as I try to add parameters for the query, I encounter an n ...

Encounters an undefined error when attempting to access a non-existent value within a nested object in Vue.js

I am currently facing an issue with accessing a nested object property. Here is the scenario: const data={a:'value1',b:{c:'null'}} When trying to access the 'c' property within object 'b', I am encountering a proble ...

Convert an array of JSON objects into a grid formatted time table using the

I am using Next.js 10 to create a timetable or schedule similar to the one below: bus stop time 1 time 2 time 3 {props[0].bus stop} {props[0].times[0]} {props[0].times[1]} {props[0].times[2]} ... {props[1].bus stop} {props[1].times[0]} {props[1] ...

Glitchy/Crazy CSS3 Animations

Currently, I am developing a website at . One of the features I have implemented is CSS3 transitions for route changes, but this feature only works in Chrome. Here's how the animation works: I apply the .preanimate class to rotate the phasing out di ...

Exploring JSON and jQuery to Address Filtering Challenges

Excuse the interruption, but I need some assistance with my filters. Below is the code I'm currently working on; however, none of my attempts have been implemented yet (the dropdown menu and checkboxes remain non-functional) to make it easier for you ...

"The jQuery colorpicker function is not functioning properly when applied to newly added elements

I've got these amazing gadgets with a cool sliding box feature inside. Initially, there are two widgets visible on the page, but you have the option to add or delete a widget as needed. Within the sliding box, there is a color picker tool. Interestin ...

How can I modify the dot colors on a graph using chart.js?

Need assistance with changing the color of graph data points https://i.sstatic.net/QGJBv.png Here is my JavaScript code snippet I have successfully created a graph using chart.js. However, I now want to differentiate data points by displaying different c ...

What is the process of memory allocation for variables in Javascript?

Can you explain to me how local variables are allocated memory in JavaScript? In languages like C and C++, local variables are typically stored on the stack. Is this also the case with JavaScript, or are all variables stored in the heap? ...

Create a JavaScript button that redirects to a different page within a React application

I am creating a div element using a for-loop and I want to link each div to the "/campaign" page with its respective id. When a div is clicked, I want it to navigate to the "/campaign/id" page and pass the id to the Campaign component. class Home extends ...

Starting on the Legacy 1.2.0.RC4 TideSDK: Where to Begin?

I just acquired the legacy version 1.2.0.RC4 from the official website. Now that I have it downloaded, what are the next steps? How can I begin using it? ...

Showing errors from model state on Razor views following an ajax request

Currently, I am working on a razor view which utilizes @Html.ValidationMessageFor helpers and has jquery unobtrusive validation setup. My goal is to invoke a controller/action and display any model state errors that may be returned by the action while adh ...

Obtaining an array through an AJAX request in JavaScript

I'm struggling with my ajax call setup: request = new XMLHttpRequest(); request.open("GET","/showChamps?textInput=" + searchChamp.value,true); request.send(null); request.onreadystatechange = function () { if (request.status == 200 && reques ...

Perform a database query upon clicking a link while simultaneously loading the link's URL

Query: Can a database query be triggered using an <a> tag while still directing the visitor to the <a> tag's URL? One approach could involve directing all links to a specific page that stores the URL of the link. Before redirecting the us ...