NoRyb
NoRyb

Reputation: 1544

Browser Back-Button jump to last location (like maps.google.com)

What I do is I go to a location in Google Maps (either by searching or just by dragging the map). Now I enter another URL in the addressbar and hit return to go to that site.

When I use the browser Back-Button, google Maps automatically switches back to the location I was last in.

How is this done if I dragged the map and didn't use some kind of "POST" on the Google Maps site? I would like to have the same behaviour in my own google Google Maps App.

I'm using Google Maps API for JavaScript v3

Upvotes: 1

Views: 2248

Answers (2)

Turek
Turek

Reputation: 78

First of all you just look for an event called 'dragend' on your map

google.maps.event.addListener(map, 'dragend', function() {

});

Then you need to get your coordinates using getCenter() and redirect your browser to '#coordinates' it won't reload your window as you use hash, but it will save it in history.

coords = map.getCenter();
window.location = '#' + encodeURI(coords);

Now you need to add listener to check for any 'hash' changes in an URL (assuming you have jQuery)

$(window).bind('hashchange', function () {
    var hash = window.location.hash.slice(1);
});

At the end you need to tell your map to change coordinates and decode url

hash = decodeURL(hash);
map.panTo(hash);

Instead of panTo() you could use setCenter(), but it add some nice animation while clicking Back button.

It is very easy to change this code to work with your searched place, you can use event 'center_changed' instead of 'dragend' and it will handle everything.

Everything I wrote about is covered here:

https://developers.google.com/maps/documentation/javascript/reference#Map

Hope this helps you.

Upvotes: 0

Kornel
Kornel

Reputation: 100170

I don't know if GMaps has convenience method for this, but generally such functionality is based on HTML5 history.pushState() which lets you add custom steps to navigation history and observe when user navigates back:

https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history

If you want to handle more advanced application states this way, there are several frameworks built on top of it, e.g. Backbone router, LeviRoutes.

In HTML4 browsers pushState can be emulated with fragment identifiers (hash URLs).

Upvotes: 1

Related Questions