refresh markers - Google Maps JavaScript API v3 - javascript

i'm refreshing an array of markers every 5 seconds using the setInterval function.
I need to compare the two arrays (before/after the refresh) in order to select which markers will be added (or removed) to the map. Is there any efficent way to do it (beyond the classical approach of two chained for loops)?
Deleting all markers before the refresh is automatically closing the infowindow (which is not desirable).
thanks

Refer this discussion
JavaScript array difference
.i think Joshaven Potters answer gives solution for u.

Related

How to filter Mapbox Markerclusters?

Since layers are projections of the source, and clusters are basically layers too, filtering the layers have no effect on the clustering, and the filtered out objects will still be visible on the cluster layers
Honestly it gave me a lot of trouble to figure out, and I came to a kind of hacky solution, but it works, and gives your application a lot better performance than manually filtering your GeoJSON features.
The Mapbox devs gave us the possibility to filter sources, but you cannot call .setFilters() on it later, there is basically no proper way to dynamically update it, which would be completely necessary to make a marker filtration function work.
If you use a dynamic filter, updating it will have no effect on your source, however, once you update the source content itself, it will update the filter as well.
So you want to initialize your source with a similar filter:
filter: ['match', ['get', 'layerType'], this.filteredLayers, true, false],
With this filter your GeoJSON features need a layerType field in properties, and if the filteredLayers array has it, it will be displayed.
You have to separately store your source data to be able to update it again the following way (or you can wait for the next iteration if you are using real time data for example).
this.filteredLayers.push('restaurants');
this.map.getSource('places').setData(data);
With this method you don't need a layer filtration logic, you only write filters like this to the source itself, and the clusters will properly display the visible data only too.
Another important thing is here that once you create a new array instance, the whole thing breaks. You must use .push() and .pop() only to filter the data.
You can write a filter removal function by sorting the filters first, and then popping them out one by one.
I've seen many people struggling with this issue and couldn't find this solution online, so I thought I would share.

ng Leaflet Directive issue with ngRepeat + map.invalidateSize()

I have a page that generates a series of maps based off of an async call. When the maps first load, they are missing tiles, as seen in the below image.
I can resolve this by calling map.invalidateSize() to redraw the tiles in each. Currently I create 8 on load and the rest are paginated via an Angular directive. Toggling to any other 8 or switching back and forth will "fix" the first 8.
Since these first 8 are the product of an ngRepeat, they all have the same ID. I could, in theory, add the index or some other string modification to the ids of each of the 8 maps and create a loop of the below code to run map.invalidateSize() on each, but this seems like a roundabout and overall poor solution to the issue. Does anyone have a better suggestion?
leafletData.getMap('leafletMap-trips').then(function(map) {
setTimeout(function () { map.invalidateSize() });
});
As a matter of fact, nope. The leaflet API only allow size invalidation per-map, so you will pretty much need to do as you explained.

How to load 1000+ Google Earth markers effectively?

I have an array that contains over 1000+ markers for Google Earth.
At the moment I am looping through the array with a for loop which is causing the Earth to freeze until they have all loaded successfully.
Can anyone recommend the best way to handle this so it loads a lot quicker for visitors?
Ideally I was thinking of loading only those markers in view/bounds but haven't seen any documentation to support this idea.
Any help would be greatly appreciated!
Thanks
I would advise you to use HTML5 WebWorkers to instantiate the markers asynchronously and then just use whatever method they have for show()/hide(), iterating through your objects.
It will only work in latest browsers, that implement WebWorkers, but i don't think there is another efficient way
One possibility is to instead do this from the server using KML Updates:
https://developers.google.com/kml/documentation/updates
Each update would load in 100 markers, say, and display them and then a second later it reloads and pulls the next 100 markers.

What is the Proper Way to Destroy a Map Instance?

I recently developed an html5 mobile application. The application was a single page where navigation hash change events replaced the entire DOM. One section of the application was a Google Map using API v3. Before the map div is removed from the DOM, I want to remove any event handlers/listeners and free up as much memory as possible as the user may not return to that section again.
What is the best way to destroy a map instance?
I'm adding a second answer on this question, because I don't want to remove the back and forth we had via follow-up comments on my previous answer.
But I recently came across some information that directly addresses your question and so I wanted to share. I don't know if you are aware of this, but during the Google Maps API Office Hours May 9 2012 Video, Chris Broadfoot and Luke Mahe from Google discussed this very question from stackoverflow. If you set the video playback to 12:50, that is the section where they discuss your question.
Essentially, they admit that it is a bug, but also add that they don't really support use cases that involve creating/destroying successive map instances. They strongly recommend creating a single instance of the map and reusing it in any scenario of this kind. They also talk about setting the map to null, and explicitly removing event listeners. You expressed concerns about the event listeners, I thought just setting the map to null would suffice, but it looks like your concerns are valid, because they mention event listeners specifically. They also recommended completely removing the DIV that holds the map as well.
At any rate, just wanted to pass this along and make sure it is included in the stackoverflow discussion and hope it helps you and others-
The official answer is you don't. Map instances in a single page application should be reused and not destroyed then recreated.
For some single page applications, this may mean re-architecting the solution such that once a map is created it may be hidden or disconnected from the DOM, but it is never destroyed/recreated.
Since apparently you cannot really destroy map instances, a way to reduce this problem if
you need to show several maps at once on a website
the number of maps may change with user interaction
the maps need to be hidden and re-shown together with other components (ie they do not appear in a fixed position in the DOM)
is keeping a pool of map instances.
The pool keeps tracks of instances being used, and when it is requested a new instance, it checks if any of the available map instances is free: if it is, it will return an existing one, if it is not, it will create a new map instance and return it, adding it to the pool. This way you will only have a maximum number of instances equal to the maximum number of maps you ever show simultaneously on screen.
I'm using this code (it requires jQuery):
var mapInstancesPool = {
pool: [],
used: 0,
getInstance: function(options){
if(mapInstancesPool.used >= mapInstancesPool.pool.length){
mapInstancesPool.used++;
mapInstancesPool.pool.push (mapInstancesPool.createNewInstance(options));
} else {
mapInstancesPool.used++;
}
return mapInstancesPool.pool[mapInstancesPool.used-1];
},
reset: function(){
mapInstancesPool.used = 0;
},
createNewInstance: function(options){
var div = $("<div></div>").addClass("myDivClassHereForStyling");
var map = new google.maps.Map(div[0], options);
return {
map: map,
div: div
}
}
}
You pass it the starting map options (as per the second argument of google.maps.Map's constructor), and it returns both the map instance (on which you can call functions pertaining to google.maps.Map), and the container , which you can style using the class "myDivClassHereForStyling", and you can dinamically append to the DOM.
If you need to reset the system, you can use mapInstancesPool.reset(). It will reset the counter to 0, while keeping all existing instances in the pool for reuse.
In my application I needed to remove all maps at once and create a new set of maps, so there's no function to recycle a specific map instance: your mileage may vary.
To remove the maps from the screen, I use jQuery's detach, which doesn't destroy the map's container .
By using this system, and using
google.maps.event.clearInstanceListeners(window);
google.maps.event.clearInstanceListeners(document);
and running
google.maps.event.clearInstanceListeners(divReference[0]);
divReference.detach()
(where divReference is the div's jQuery object returned from the Instance Pool)
on every div I'm removing, I managed to keep Chrome's memory usage more or less stable, as opposed to it increasing every time I delete maps and add new ones.
I would have suggested removing the content of the map div and using delete on the variable holding the reference to the map, and probably explicitly deleteing any event listeners.
There is an acknowledged bug, though, and this may not work.
As google doesnt provide gunload() for api v3 better use iframe in html and assign map.html as a source to this iframe. after use make src as null. That will definitely free the memory consumed by map.
When you remove the div, that removes the display panel and the map will disappear. To remove the map instance, just make sure that your reference to the map is set to null and that any references to other parts of the map are set to null. At that point, JavaScript garbage collection will take care of cleaning up, as described in: How does garbage collection work in JavaScript?.
I guess you're talking about addEventListener. When you remove the DOM elements, some browsers leak these events and doesn't remove them. This is why jQuery does several things when removing an element:
It removes the events when it can using removeEventListener. That means it's keeping an array with the event listeners it added on this element.
It deletes the attributes about events (onclick, onblur, etc) using delete on the DOM element when addEventListener is not available (still, it has an array where it stores the events added).
It sets the element to null to avoid IE 6/7/8 memory leaks.
It then removes the element.

Making Google Maps driving directions behave more like actual Google Maps

I've been doing driving directions in my map app using the directionsRenderer, so it renders both the path (on the map) and the html list of directions. My app works basically like this example: http://code.google.com/apis/maps/documentation/javascript/examples/directions-draggable.html
However, now I've been asked to make it a little more like the directions on Google Maps proper, for instance here
My client would like the little popups when you hover over the html items, as well as the little icons showing right turn, bear left, merge, etc.
I've managed to render my own html from the DirectionsService response, and hook up events for hovering and associate them with points on the map, but where I could use help is:
Getting the turn by turn icons. I imagine this isn't easy because I get each step as html text ("Take exit 433 on the left to merge onto I-80 E toward Bay Bridge/Oakland"), and I imagine that could be challenging to parse reasonably to determine which icon to show
Making the little mini-popups over the map. Although I can make the popups themselves, it's probably challenging or impossible to do it the exact same way because I don't have a short version of the instructions.
In any case, I thought I'd check if anyone knows a way to do this sort of thing -- not necessarily exactly, but just closer to it -- or if I'm just out of luck because google hasn't made any of that sort of functionality available via their api.
You are correct that you will have to examine strings to get turn icons. You can parse the DirectionsResult object yourself (it is "JSON-like" according to Google's documentation) rather than using the DirectionsRenderer if you wish, but I don't think it will get you anything much. Here's how it would go:
The DirectionsResult.route property will be an array of DirectionsRoute objects. If you didn't set provideRouteAlternatives to true, then there will only be one DirectionsRoute object in the array.
The DirectionsRoute object, in turn, has a property called legs. That property is an array of DirectionsLeg objects. If you have specified no waypoints (i.e., an intermediary destination), just a start and end point, then this array will also only have one object in it.
The DirectionsLeg object, in turn, has a property called steps. It will be an array where each element will be a DirectionsStep object.
The DirectionsStep object has a property called instructions. That is a string and is what you will have to examine using a regexp or whatever to figure out what turn icon to use. (It's possible that this may be easier to work with than the HTML you mention that I imagine is coming from the DirectionsRenderer. Or it may be possible that it isn't any easier whatsoever. I'm not sure. I've never actually done it.)

Categories

Resources