Check out the demo here.
In this example I am showing how we can move marker on Google Map. This example is inspired by twittervision.com. Here we are changing information on Marker and moving it on Google Map using AJAX and JavaScript. We are refreshing the list of available updates from server in a fixed interval.
1. HTML File
<!--index.html--> <html> <head> <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAMEzhSKcWoYFZdcgJ2yb9VhQfbBedyeTcqIokiCHhEBJKH_N_NRTEMzJanHbfvVY9Llw4oYuILWGf5Q" type="text/javascript"></script> <script src="prototype.js" type="text/javascript"></script> <script src="script.js" type="text/javascript"></script> <style type="text/css"> .map { width: 800px; height: 400px; border:#666666 thin dashed; padding: 0; background: #FFFFFF; margin-right: auto; margin-bottom: 10px; margin-left: auto; } #lastStatus { font-size:12px; font-family: verdana, arial, helvetica, sans-serif; color:#333; padding:5px; } #infoWindow { width:350px; text-align: left; } #infoWindow tip { float: right; } </style> </head> <body> <div id="map" class="map"></div> </body> </html>
2. JavaScript File
//script.js var infos = []; var loading = false; var displayCount = 0; function Info (infoArray) { var infoVars = [ 'latitude', 'longitude', 'location_name', 'text']; for (var i = 0; i < infoVars.length; i++) { this[infoVars[i]] = infoArray[i]; } } Info.prototype.lastStatus = function () { var myDiv = document.createElement('div'); myDiv.innerHTML = this.text; myDiv.id = "lastStatus"; return myDiv; } Info.prototype.infoWindow = function() { var myInfoWindow = document.createElement('div'); myInfoWindow.id = "infoWindow"; myInfoWindow.appendChild(this.lastStatus()); return myInfoWindow; } function loadData() { if (!loading) { new Ajax.Request('updates.php', { method : 'post', onCreate : function () { loading = true; }, onSuccess : function(transport) {addInfos(transport.responseText);}, onComplete : function () { loading = false; } }); } } function showInfos() { var currentInfo = infos.pop(); if ( currentInfo && currentInfo.show ) { currentInfo.show(); displayCount++; } if (infos.length == 0) loadData(); setTimeout("showInfos();", 5000); } function addInfos(responseText) { var newInfos = eval(responseText); if (newInfos.length == 0) alert("No Infos Available!"); else { for (i=0; i<newInfos.length; i++) { infos.push(new Info(newInfos[i])); } } if (displayCount == 0) showInfos(); } var map; var userMarker; var marker; var map_icon = addOptionsToIcon(new GIcon(),{iconSize : new GSize(48,48), iconAnchor : new GPoint(18,43), infoWindowAnchor : new GPoint(45,20), image : '/images/icon.png', shadow : '/images/birdshadow.png'}); // add options to a GMaps icon function addOptionsToIcon(icon, options) { for(var k in options) { icon[k] = options[k]; } return icon; } function loadMap () { var w = 800; // Width of map container map = new GMap2(document.getElementById("map"), {mapTypes: [G_PHYSICAL_MAP] }); map.setCenter(new GLatLng(39,76), w>700 ? 3 : 2); map.addControl(new GSmallMapControl()); } Info.prototype.show = function () { // clear marker map.closeInfoWindow(); if (marker) map.removeOverlay(marker); // show marker with infoWindow marker = new GMarker(new GLatLng(this.latitude,this.longitude), { icon : map_icon }); map.addOverlay(marker); map.openInfoWindow(marker.getLatLng(), this.infoWindow(), {noCloseOnClick : true, pixelOffset : new GSize(25,-22) } ); } addEvent(window, 'load', init); function init() { if (GBrowserIsCompatible()) { loadMap(); loadData(); } else { alert("Sorry, your browser isn't compatible with Google Maps!") } } function addEvent(obj, evType, fn){ if (obj.addEventListener){ obj.addEventListener(evType, fn, false); return true; } else if (obj.attachEvent){ var r = obj.attachEvent("on"+evType, fn); return r; } else { return false; } }
3. PHP File
<?php //updates.php header('Content-Type: text/javascript; charset=utf-8'); $info[] = array(34.1372273,-117.7023255,"Los Angeles, New Orleans", "Manny Pacquaio's two-round demolition of Ricky Hatton has set up the prospect of the biggest money-spinning fight in the history of boxing."); $info[] = array(52.6449251,-0.6424268,"England near Rutland Water", "Liverpool, with returning captain Steven Gerrard back in the side, were always in control against a disappointing Newcastle -- who have still to collect their first victory under temporary manager Alan Shearer."); $info[] = array(37.775,-122.418333,"San Francisco", "Dirk Kuyt squared a dangerous ball into the six-yard box and Israeli Benayoun slid home his fourth goal from seven games, as three defenders stood and watched."); $info[] = array(40.757929,-73.985506,"New York, NY", "That lead was doubled just six minutes later when Gerrard's corner was met with a superb diving header from Dutchman Kuyt, giving Steve Harper no chance in the Newcastle goal."); $info[] = array(48.751448,-122.472574,"bellingham, wa", "Xabi Alonso hit the crossbar for Liverpool with a curling 30-yarder as Newcastle struggled to get a foot-hold on the game."); $info[] = array(45.823041,6.197545,"Here.", "Alonso was stretchered off following that tackle and his replacement Lucas Leiva added a third goal in the 88th-minute when heading home Fabio Aurelio's free-kick."); $info[] = array(39.755092,-104.988123,"Los Angeles", "The result leaves Liverpool three points behind leaders Manchester United, although Alex Ferguson's side have a game in hand."); $info[] = array(27.800278,-97.396111,"corpus christi", "Meanwhile, Newcastle remain second bottom on 31 points, level with north-east rivals Middlesbrough who they face next weekend in a crucial showdown, with just three matches remaining."); echo json_encode($info); ?>

#1 by tushar - July 27th, 2009 at 12:55
hi akchauhan !
Please help me out!
I have tried your twitter vision code and i am getting error in updates.php: echo json_encode($info);
The json encode function is not working on my system and its showing fatal error.
Also i wanted to just pass address through database without latitude and longitude.
Please provide me a working total solution.
Thanks in advance
#2 by admin - July 28th, 2009 at 14:39
@ tushar
I think either you are using PHP < 5.2 or JSON library in not enabled in your php.ini file. If you are using PHP version <5.2 you can use this user defined function "array_to_json" instead of "json_encode"
function array_to_json( $array ){
if( !is_array( $array ) ){
return false;
}
$associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
if( $associative ){
$construct = array();
foreach( $array as $key => $value ){
// We first copy each key/value pair into a staging array,
// formatting each key and value properly as we go.
// Format the key:
if( is_numeric($key) ){
$key = “key_$key”;
}
$key = “‘”.addslashes($key).”‘”;
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = “‘”.addslashes($value).”‘”;
}
// Add to staging array:
$construct[] = “$key: $value”;
}
// Then we collapse the staging array into the JSON form:
$result = “{ ” . implode( “, “, $construct ) . ” }”;
} else { // If the array is a vector (not associative):
$construct = array();
foreach( $array as $value ){
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = “‘”.addslashes($value).”‘”;
}
// Add to staging array:
$construct[] = $value;
}
// Then we collapse the staging array into the JSON form:
$result = “[ " . implode( ", ", $construct ) . " ]“;
}
return $result;
}
If you are only sending address then you have to find out the longitude and latitude of the addresses to point addresses to Google Map. Google provide service for this and you can find out more about it on http://code.google.com/apis/maps/documentation/.
#3 by Alok Jain - August 3rd, 2009 at 16:32
Hello Chauhan,
Please help me out!
I have created Same as twittervision.com but i am not able to hide/remove marker icon. Will you please help me out from this problem.
In advance Thank you.
Thanks & Regards,
Alok Jain
#4 by Alok Jain - August 3rd, 2009 at 17:10
Hello Chauhan,
Please help me out!
I have created Same as twittervision.com but i am not able to hide/remove marker icon. Will you please help me out from this problem.
Url: http://202.71.142.164/nauna/?module=Users&action=MapFeeds&feed=location
In advance Thank you.
Thanks & Regards,
Alok Jain