Making Google Maps driving directions behave more like actual Google Maps - javascript

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.)

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.

Google Maps API and DynamicMapsEngineLayer: Loop Over Features in the Map

[Edit APRIL 2, 2014]
I want to emphasize something. My scenario does not have a user event driving it to trigger an event listener. I know the Maps API documentation shows how to get a feature's featureId property from a MapsEngineMouseEvent. But my scenario needs to get the feature's featureId programmatically.
I've also tried programmatically "faking" a click, but that doesn't work either. (It seems the event object can't be instantiated??)
My hunch is, the solution to this either 1) doesn't exist, 2) is deceptively simple, or 3) will only be discovered if a minimum level 8 mage rolls a natural 20 wisdom check..
[Original Problem Statement]
I have few scenarios in a customized Google Maps client where I need to loop over features in a DynamicMapsEngineLayer and modify their style traits. The DynamicMapsEngineLayer works by performing..
..client-side rendering of vector data, allowing the developer to
dynamically restyle the vector layer in response to user interactions
like hover and click.
The Maps API documentation describes how to restyle individual features using event listeners, which expose a special featureId value assigned by Google servers. But my scenario doesn't have user-driven events. For example, consider this hypothetical link:
http://www.acme-map.com/index.php?ZoomToAndHighlightFeatureWithId=12345
FeatureWithId is our own unique id, not Google's special
featureId, which we don't have at this point in the runtime.
I need the map to load right above a feature and highlight it by changing its style trait. It needs to do this programmatically when the map first loads, without any user interaction. If these vector features are truly rendered in the DOM, then surely there's a way, no matter how cryptic, to reach into the map's guts and access these objects?
Is there a way to loop over individual features in a DynamicMapsEngineLayer or get the featureId property without an event listener?
I may be missing something here, but if you already know the feature ID, you can restyle it directly without an event. Just call getFeatureStyle() directly and set the style as you wish:
var style = dynamicLayer.getFeatureStyle('1234');
style.strokeColor = '#FF0000';
style.iconImage = 'url(images/myIcon.png)';
And if you don't know the feature ID, but you do have some other attribute to query against, you can make a call out to the Maps Engine API to fetch it.

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.

Why is my isometric map code not being called?

I'm building an isometric map like the one done by Christian Weber.
I've got nearly identical code to his, but the JS function building the map is never getting called. It should be, since I have $('div#map').gameMap({map:[[{"tile":"grass_0","object":""},... in the $(document).ready(function()
{} like he does in his demo's source code.
Here's a JSFiddle showing my attempt: http://jsfiddle.net/briz/RWgge/6/
I only need 1 map, and it doesn't need to be as big as the one given in the code, but for the purpose of trying to make the map work, I've kept it the same large map as he gives.
Can someone understand why my gameMap func is not being called?
Your code is in the wrong order -- you need to load the plugin before you create a class using it, and you need to create an instance of the class after you've created the class.
Is this what you wanted?
http://jsfiddle.net/mblase75/RWgge/8/

Suggestion for creating tooltips on an image

Is there an alternative (and more elegant!) method of creating multiple tooltips on top of an image without using image maps? Preferably looking for a solution that makes use of jQuery, but not necessary.
While I know solutions exist with image maps, they just seem so clunky and unmaintainable. For example, what if the image comes from a dynamic source? Would that source also have to provide an image map as well, which someone would then have to create beforehand? Maybe I'm asking for too much, but on the chance that someone out there has a more elegant solution to this, I'd be very grateful.
Thanks for you help!
I understand your question, but there are two few things that we cannot break from.
Your images might be loaded dynamically
Tool-tip areas can be points, boxes, or basically ANY shape (a set of coordinates that binds a region)
Because of #2, it's impossible but to use an image map. If, however, your tool-tip areas are restricted to points and boxes, then you can make do without creating an image map. This doesn't mean that the image source doesn't have to provide any information because that doesn't make sense, it just means that the source can provide a generic JSON object that talks about the image. Once the image reaches client side, you can call a function that you wrote to create an invisible div on top of your image and based on the data you've received, create small div regions that have mouseenter() bound to them. Even with this, it's not FAR from an image map.
I guess the point I'm trying to make is that you are not getting away from having to attach data to your image AND do some processing of that data once it reaches client side. This is because you're working with such an unrestricted environment of an image that can take on any shape with your regions taking on any shape.
I'm not sure if this answers your question in any way, but usually elegance comes from taking advantage of restrictions, which in this case there is practically nothing we can work with.

Categories

Resources