Shaun Mccran

My digital playground

11
J
A
N
2011

Google maps panning example

I've been tinkering with the Google Maps Api recently, in an effort to replicate a flash project I've seen. It was a Google maps interface that used Adobe livecycle (http://www.adobe.com/products/livecycle/) feeds to poll IP addresss and display them within the map interface.

I liked the look of it, but wanted to create it in JQuery as it required a lot of custom server side code, and several expensive server software installations. Also I'm migrating away from the flash / flex arena into a more purist JQuery / AJAX development mindset.

There is a full example of Google Maps panning here

First off we need to setup our page, Google maps requires an API key, so I'm setting that using ColdFusion, and passing it on the URL to the Google JavaScript API call. This validates against your URL, and is free. If you don't have one, you can get one here: http://code.google.com/apis/maps/signup.html.

After this I'm loading JQuery and the maps JS.

view plain print about
1<cfset request.apiKey = "your key here">
2
3<s/cript type="text/javascript"src="http://www.google.com/jsapi?key=<cfoutput>#request.apiKey#</cfoutput>"></script>
4
5<s/cript type="text/javascript">
6    google.load("jquery", '1.3');
7    google.load("maps", "2.x");
8</script>

The next block of code is the html content of the page. It is really small as most of our content will be dynamically inserted from the Google Maps functions.

The important bits are the 'map' div, which will hold our map graphics, and the ul 'list' container. This will be populated with a series of random Geo points from Google maps.

view plain print about
1<div id="wrapper">
2
3    <div id="map"></div>
4    <ul id="list">
5        <div id="header">Random points</div><br id="clear-all">
6    </ul>
7
8    <div id="message" style="display:none;">
9        Label
10    </div>
11
12</div>

Now we can create our map and assign it to our container ('map'). Next I have created a variable called 'cheltenham' , which has the lat long of (yes you guessed it!) the town of Cheltenham. This is the initial starting point for the map. Lastly we use the setCenter method to position the map, and set the starting zoom level

view plain print about
1<s/cript type="text/javascript">
2    $(document).ready(function(){
3
4// set the element 'map' as container
5var map = new GMap2($("#map").get(0));
6
7// set the lat long for the center point
8var cheltenham = new GLatLng(51.89487062921521,-2.084484100341797);
9
10// value 1 is the center, value 2 is the zoom level
11map.setCenter(cheltenham, 9);

Now we will create ten random points on the map. The idea is to display the panning function, so I don't really care where they are. We get the boundaries of the map, then we convert them to lat long coordinates, then we loop over them ten times invoking the map.addOverlay to create new markers each time.

view plain print about
1// setup 10 random points
2    var bounds = map.getBounds();
3    var southWest = bounds.getSouthWest();
4    var northEast = bounds.getNorthEast();
5    var lngSpan = northEast.lng() - southWest.lng();
6    var latSpan = northEast.lat() - southWest.lat();
7    var markers = [];
8    
9for (var i = 0; i < 10; i++) {
10    var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
11            southWest.lng() + lngSpan * Math.random());
12            marker = new GMarker(point);
13            map.addOverlay(marker);
14            markers[i] = marker;
15        }

Next we will create a function to handle each of the markers. This function populates the ul list created above with a list of the markers. It also attached a click event to each marker that uses the function 'displayPoint', passing in the marker reference and index.

view plain print about
1// markers click event
2    $(markers).each(function(i,marker){
3        $("<li />")
4            .html("Point "+i)
5            .click(function(){
6                displayPoint(marker, i);
7                })
8                .appendTo("#list");
9                    
10            GEvent.addListener(marker, "click", function(){
11                displayPoint(marker, i);
12            });
13        });

Now we create the displayPoint function referenced above. This has an event listener to watch for the end of a move event. It also calculates to distance from the current position to the clicked marker. It then uses the panTo method to pan the map display to the selected marker. (marker.getLatLng).

view plain print about
1function displayPoint(marker, index){
2    $("#message").hide();
3                    
4    var moveEnd = GEvent.addListener(map, "moveend", function(){
5    var markerOffset = map.fromLatLngToDivPixel(marker.getLatLng());
6    $("#message")
7        .fadeIn()
8        .css({ top:markerOffset.y, left:markerOffset.x });
9                    
10        GEvent.removeListener(moveEnd);
11        });
12    map.panTo(marker.getLatLng());
13    }

It looks like a wedge of code, but if you view the source of the demo below it is pretty small.

In the next post I will add the AJAX polling to dynamically get the markers from a datasource.

There is a full example of Google Maps panning here

Related Blog Entries

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
# Posted By google satellite maps | 05/05/2011 23:10
Shaun's Gravatar Thanks, I'll check it out, always good to see variations on a theme.
# Posted By Shaun | 05/05/2011 23:13
Best Plumbing's Gravatar In the next post I will add the AJAX polling to dynamically get the markers from a datasource.
# Posted By Best Plumbing | 23/11/2015 03:43
learn more here's Gravatar Thursday in November and January, and $19 on Fridays and Saturdays for those months and all of December. Adult tickets are always $29. Hotel packages are available
# Posted By learn more here | 24/11/2015 01:51
read full report's Gravatar n the next post I will add the AJAX polling to dynamically get the markers from a datasource.
# Posted By read full report | 24/11/2015 01:57
the venus factor review youtube's Gravatar the best service for the students. these service will surely help the students to get a better knowledge about their academic paper.
# Posted By the venus factor review youtube | 24/11/2015 04:27
Kelowna Siding Contractor's Gravatar We have now mastered the theoretical part, now it remains to verify and put your knowledge into practice in one of our hotel restaurants and bars.
# Posted By Kelowna Siding Contractor | 26/11/2015 04:35
special info's Gravatar I just thought it may be an idea to post in case anyone else was having problems researching but I am a little unsure if I am allowed to put names and addresses on here.
# Posted By special info | 13/12/2015 22:18
Xareltos Side Effects Runied your Life?'s Gravatar I'm able to bookmark your site and show the kids check out up here generally. I m fairly positive there likely to be informed a great deal of new stuff here than anyone.
# Posted By Xareltos Side Effects Runied your Life? | 19/12/2015 02:20
E3-1240v2's Gravatar nstant Switch review said: I know your expertise on this. I must say we should have an online discussion on this.
# Posted By E3-1240v2 | 19/12/2015 23:20
Assistant Course's Gravatar Great Post This is also a very good post which I really enjoyed reading. It is not everyday that I have the possibility to see something like this..Thank You!
# Posted By Assistant Course | 21/12/2015 02:41
san diego dui's Gravatar I just thought it may be an idea to post in case anyone else was having problems researching but I am a little unsure if I am allowed to put names and addresses on here.
# Posted By san diego dui | 22/12/2015 04:46
home remedies for tmj's Gravatar Thanks meant for sharing this type of satisfying opinion, written piece is fastidious, that’s why I’ve read it completely.
# Posted By home remedies for tmj | 25/12/2015 14:07
buy custom term papers's Gravatar Firstly create a CurrencyFormatter object, and specify the currency symbol, and any other formatting parameters that you require.
# Posted By buy custom term papers | 26/12/2015 02:20
cause of tinnitus's Gravatar This blog is so nice to me. I will continue to come here again and again. Visit my link as well. Good luck...
# Posted By cause of tinnitus | 26/12/2015 05:41
pure slim cleanse's Gravatar This is the initial starting point for the map. Lastly we use the setCenter method to position the map, and set the starting zoom level
# Posted By pure slim cleanse | 27/12/2015 05:36
click here's Gravatar Good to become visiting your weblog again, it has been months for me. Nicely this article that i've been waited for so long.
# Posted By click here | 28/12/2015 01:59
click here's Gravatar Your site and show the kids check out up here generally. I m fairly positive there likely to be informed a great deal of new stuff here than anyone.
# Posted By click here | 29/12/2015 01:41
targeted traffic's Gravatar I’m now working with WordPress for a couple of with this blogs and forums nonetheless wanting to switch one of them over to your stand akin to you for a trial offer perform.
# Posted By targeted traffic | 04/01/2016 23:27
Ranveer's Gravatar Your blog was too good. i really appreciate with your blog.Thanks for sharing.
http://iplauction2016.in/
http://icct20worldcup2016live.org/
http://icct20worldcup2016tickets.com/
# Posted By Ranveer | 07/01/2016 01:09
amazon product research tool's Gravatar I have feel that this blog is really have all those quality that qualify a blog to be a one.I wanted to leave a little comment to support you and wish you a good continuation.
# Posted By amazon product research tool | 09/01/2016 01:01
Back to top