My index.php file is shown below. In which I want to show a map and multiple marker on it using json object. This code is only for one marker. Could u please tell me how can be this code modify for multiple markers and how can i access json object in $.ajax()??
<!DOCTYPE html>
<html>
<head>
<style>
#map { width: 1000px;height: 500px;}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
var latlng = {lat: 31.566470, lng: 74.297723};
var marker;
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: latlng,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: latlng,
title: "Hello World!",
map: map // replaces marker.setMap(map);
});
// now let's set a time interval, let's say every 3 seconds we check the position
setInterval(
function() {
// we make an AJAX call
$.ajax({
dataType: 'JSON', // this means the result (the echo) of the server will be readable as a javascript object
url: 'final.php',
success: function(data) {
// this is the return of the AJAX call. We can use data as a javascript object
console.log(data);
// now we change the position of the marker
marker.setPosition({lat: Number(data.lat), lng: Number(data.lng)});
},
error(error) {
console.log(error);
}
})
}
, 3000
);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
and it is my final.php
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','1234');
define('DB','coordinates');
$con = mysqli_connect(HOST,USER,PASS,DB);
$arr=[];
for($x=1; $x<=3; $x++){
$query = "SELECT id, longitude, latitude FROM data WHERE bus_id= ".$x." ORDER BY id DESC limit 1" ;
$qry_result = mysqli_query($con,$query);// or die(mysqli_error());
// Insert a new row in the table for each person returned
while($row = mysqli_fetch_array($qry_result)) {
$longitude = $row['longitude'];
$latitude = $row['latitude'];
array_push($arr, [
'lat'=>$longitude,
'lng'=>$latitude,
//'recs'=>$recs
]);
}
}
$record= json_encode($arr);
echo $record;
?>
this is my json object
[{"lat":"74.348047","lng":"31.569907"},{"lat":"74.307826","lng":"31.573289"},{"lat":"74.330023","lng":"31.558144"}]
The following is not tested but I think it should work. There is a function addmarker which you call in a loop to process all data returned from the ajax call. If this gets called every few seconds you also need to clear old markers from the map - hence using an array to store references to each new marker.
I found a syntax error in original code relating to the error handler - not sure if I have corrected in the right way as I do not use jQuery ~ looks ok though.
<!DOCTYPE html>
<html>
<head>
<style>
#map { width: 1000px;height: 500px;}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
var latlng = { lat: 31.566470, lng: 74.297723 };
var marker;
var map;/* make the map available in all scopes */
var markers=[];/* container to store references to newly added markers */
function addmarker(map, lat, lng, title ){
/* add new marker */
marker = new google.maps.Marker({
position:{ lat:lat,lng:lng },
title:title,
draggable:true,
map:map
});
/*marker.setMap( map );*/
/* store reference */
markers.push( marker );
}
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: latlng,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: latlng,
title: "Hello World!",
map: map // replaces marker.setMap(map);
});
setInterval(
function() {
$.ajax({
dataType: 'JSON',
url: 'ajax.php',
success: function(data) {
/* clear old markers */
markers.forEach( function( e,i,a ){
e.setMap( null );
});
for( var o in data ){
var lat=Number(data[o].lat);
var lng=Number(data[o].lng);
/* Watch the console, see what you get here */
console.log( 'lat:%s, lng:%s',lat,lng );
addmarker.call( this, map, lat, lng, 'Hello World - a title!' );
}
},
error: function( err ){
console.log( err );
}
})
}, 3000 );
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
The full code I used in testing
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$conn = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql="select
`location_name` as 'title',
`location_map_centre_Latitude` as 'lat',
`location_map_centre_Longitude` as 'lng'
from `maps`
where `countryid`=171
order by rand()
limit 10";
$res=$conn->query( $sql );
if( $res ){
$json=array();
while( $rs=$res->fetch_object() ){
$json[]=array( 'title'=>$rs->title, 'lat'=>$rs->lat, 'lng'=>$rs->lng );
}
header('Content-Type: application/json');
echo json_encode( $json );
}
$conn->close();
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
#map { width: 1000px;height: 500px;}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>/* initial lat/lng is in Scotland, near Forfar */
var latlng = { lat: 56.61543329027024, lng: -2.9266123065796137 };
var marker;
var map;
var markers=[];/* container to store references to newly added markers */
function addmarker(map, lat, lng, title ){
/* add new marker */
marker = new google.maps.Marker({
position:{ lat:lat,lng:lng },
title:title,
draggable:true,
map:map
});
/* store reference */
markers.push( marker );
}
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: latlng,
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);
marker = new google.maps.Marker({
position: latlng,
title: "Hello World!",
draggable:true,
map: map // replaces marker.setMap(map);
});
/* for testing I only want it to run for a few times */
var i=0;
var m=10;
var igm=setInterval(
function() {
/* testing */
i++;
if( i > m ) clearInterval( igm );
/* testing */
$.ajax({
dataType:'JSON',
method: 'post',
url: document.location.href,
success: function(data) {
/* clear old markers */
markers.forEach( function( e,i,a ){
e.setMap( null );
console.log( 'remove marker:%o', e );
});
for( var o in data ){
var lat=Number(data[o].lat);
var lng=Number(data[o].lng);
var title=data[o].title;
/* Watch the console, see what you get here */
console.log( 'lat:%s, lng:%s',lat,lng );
addmarker.call( this, map, lat, lng, title );
}
},
error: function( err ){
console.warn( 'Error: %s',err );
}
})
}, 5000 );
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
example debug info from console:
remove marker:Object { __gm={...}, gm_accessors_={...}, position=(54.9094444444, -7.289444444440051), more...}
remove marker:Object { __gm={...}, gm_accessors_={...}, position=(56.306252, -3.2225129999999353), more...}
remove marker:Object { __gm={...}, gm_accessors_={...}, position=(54.9616666667, -6.9694444444400006), more...}
lat:56.6022222222, lng:-2.63416666667
lat:56.56138345735925, lng:-2.935781240463257
lat:54.5044444444, lng:-7.35222222222
Related
I am trying to display multiple markers on Google maps using data (lat and lng) from a MySQL database. When I run a foreach loop to return these markers on the map, it returns only the last row. What might be the problem?
<?php
require_once "db/db_handle.php";
$select = "SELECT * FROM map";
$data = $db->query($select);
?>
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<?php foreach ($data as $key) {
echo $key['lat'];
?>
<script>
function initMap() {
var uluru = {lat: <?php echo $key['lat']; ?>, lng: <?php echo $key['lng']; ?>};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
var contentString = '<?php echo $key['address']; ?>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: uluru,
map: map,
title: 'Uluru (Address)'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
</script>
<?php } ?>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=myKey&callback=initMap">
</script>
</body>
</html>
It will be very easy to fetch all the lat and long.
require_once "db/db_handle.php";
$select = "SELECT * FROM map";
$data = $db->query($select);
foreach ($data as $key)
$locations[]=array( 'name'=>'Location Name', 'lat'=>$key['lat'], 'lng'=>$key['lng'] );
}
/* Convert data to json */
$markers = json_encode( $locations );
Then set the google map markers using the php variable markers.
<script type='text/javascript'>
<?php
echo "var markers=$markers;\n";
?>
function initMap() {
var latlng = new google.maps.LatLng(-33.92, 151.25); // default location
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById('map'),myOptions);
var infowindow = new google.maps.InfoWindow(), marker, lat, lng;
var json=JSON.parse( markers );
for( var o in json ){
lat = json[ o ].lat;
lng=json[ o ].lng;
name=json[ o ].name;
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
name:name,
map: map
});
google.maps.event.addListener( marker, 'click', function(e){
infowindow.setContent( this.name );
infowindow.open( map, this );
}.bind( marker ) );
}
}
Overall code will be :
require_once "db/db_handle.php";
$select = "SELECT * FROM map";
$data = $db->query($select);
foreach ($data as $key)
$locations[]=array( 'name'=>'Location Name', 'lat'=>$key['lat'], 'lng'=>$key['lng'] );
}
/* Convert data to json */
$markers = json_encode( $locations );
?>
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script type='text/javascript'>
<?php
echo "var markers=$markers;\n";
?>
function initMap() {
var latlng = new google.maps.LatLng(-33.92, 151.25); // default location
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById('map'),myOptions);
var infowindow = new google.maps.InfoWindow(), marker, lat, lng;
var json=JSON.parse( markers );
for( var o in json ){
lat = json[ o ].lat;
lng=json[ o ].lng;
name=json[ o ].name;
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
name:name,
map: map
});
google.maps.event.addListener( marker, 'click', function(e){
infowindow.setContent( this.name );
infowindow.open( map, this );
}.bind( marker ) );
}
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=myKey&callback=initMap">
</script>
</body>
</html>
I am trying to include google maps on a homepage for the first time and just found the code which creates a google map with a particular location -
var myLatlng1 = new google.maps.LatLng(53.65914, 0.072050)
and I don't know how to change the location where the marker is- where can I find the location coordinates? Thanks!
<html>
<head>
<title> Map </title>
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 500px;
width: 800px;}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false">
</script>
<script>
var map;
function initialize()
{
var myLatlng1 = new google.maps.LatLng(53.65914, 0.072050);
var mapOptions =
{
zoom: 10,
center: myLatlng1,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
<?php
$sql = mysql_query("SELECT * FROM data ORDER BY ID DESC");
while($row =mysql_fetch_array($sql))
{
$desc = $row['DESCRIPTION'];
$location = $row['LOCATION'];
$counter += 1;
?>
var marker = new google.maps.Marker({
position: new google.maps.LatLng(<?php echo $location; ?>),
map: map,
title: '<?php echo $desc; ?>',
icon: '/image/cam.png'
});
navigator.geolocation.getCurrentPosition(showPosition);
}
var showPosition = function (position)
{
map.setCenter(new google.maps.LatLng(position.coords.latitude,
position.coords.longitude), 16);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
This is easy . First go to google maps and select the location you want to zoom in on. Once there look at the url at the top of the page it should look like this:
https://www.google.com/maps/#44.0005355,-71.0799974,12z
This is your lat long 44.0005355 and -71.0799974 Just replace them with the ones you have.
The portion of code that set the marker ( included the position) is this
var yourLat = 45.2323; // is only sample value
ver yourLng = 14.1818; // is only sample value
var marker = new google.maps.Marker({
position: new google.maps.LatLng(yourLat, yourLng),
map: map,
title: 'your title',
icon: '/image/cam.png'
});
You must assign the coord in google map notation so if you haven't this coord use google maps and click the point you desise. the coord appear in a box
I am working on a tracking system.
I get gps lat long values from database and then show marker on map,
and refresh a page after 30 seconds to check may b values updated on server.
my code is given below.
may map show page.
<!DOCTYPE html />
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript"> </script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<title>GoogleMaps</title>
<script>
function initialize(lang,lat) {
var myLatlng = new google.maps.LatLng(lang,lat);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var contentString = 'Location NAme';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Location NAme'
});
}
function show_map(){
$.ajax({
type: "POST",
url: "some.php"
})
.done(function( msg ) {
alert(msg);
var obj = jQuery.parseJSON(msg);
initialize(obj.lang,obj.lat);
});
}
setInterval(show_map,30000);
</script>
</head>
<body onLoad="show_map()">
<div id="map_canvas" style="width: 100%; height: 100%;">
</body>
</html>
my PHP page is:
<?php
mysql_connect("localhost","root","")or die("error in connection");
mysql_select_db("gpsvalues");
$result = mysql_query("select * from gps");
$row = mysql_fetch_assoc($result);
$arr=array();
$arr = $row;
echo json_encode($arr);
?>
But it is not works fine.
For show multiple in a map you have to create array for lat long.
var locations;
locations=[
[lat1,long1],
[lat2,long2],
[lat3,long3],
[lat4,long4],
];
So your code should be change like
<script>
var locations;
locations=[
[lat1,long1],
[lat2,long2],
[lat3,long3],
[lat4,long4],
];
var map = new google.maps.Map(document.getElementById('maparea'), {
zoom: 14,
center: new google.maps.LatLng(6.778659644259302, 79.99540328979492),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
You can call the add marker function through your php for every row in the gps..
<script>
<?php
mysql_connect("localhost","root","")or die("error in connection");
mysql_select_db("gpsvalues");
$result = mysql_query("select * from gps");
while($row = mysql_fetch_assoc($result))
{
echo "addmarker($row[lat], $row[lng]);"; //whatever way you have stored in your database
}
?>
function addmarker(lat, lng) {
var myLatlng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Location NAme'
});
marker.setMap(map);
}
</script>
i have a problem with placing multiple marker in google map.here is my code.it display only one marker during page reloading and when page is complettly load then map is not display.
javascript code:
<head>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script>
function initialize(lat,lon)
{
var myCenter=new google.maps.LatLng(lat,lon);
var mapProp = {
center:myCenter,
zoom:9,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
php code:
<?php
require_once 'geocode.php';
$addarray=array(0=>'a, ahmedabad,india',1=>'b,ahmedabad,india');
foreach($addarray as $add)
{
// define the address and set sensor to false
$opt = array (
'address' => urlencode($add),
'sensor' => 'false'
);
// now simply call the function
$result = getLatLng($opt);
// if status was successful, then print the lat/lon ?
if ($result['status']) {
echo '<pre>';
?>
<script>
initialize(<?php echo $result['lat'];?>,<?php echo $result['lon'];?>);
</script>
<?php
echo '</pre>';
}
}
?>
here first i got lat and lon according to address then i called javascript function to place marker.but something is missing or create a problem.
thanks in advance.
Thanks #Tudor Ravoiu for your help. it is solved by changing few things.
i have created array in json format in php and pass it to javascript.
<?php
require_once 'geocode.php';
$addarray=array(0=>'a,ahmedabad,india',1=>'b,ahmedabad,india',2=>'c,ahmedabad,india');
$lat1=array();
foreach($addarray as $add)
{
// define the address and set sensor to false
$opt = array (
'address' => urlencode($add),
'sensor' => 'false'
);
// now simply call the function
$result = getLatLng($opt);
// if status was successful, then print the lat/lon ?
if ($result['status'])
{
array_push($lat1,array($result['address'],$result['lat'],$result['lon']));
}
}echo json_encode($lat1);
?>
javascript code:
<script type="text/javascript">
var locations = <?php echo json_encode($lat1);?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
You have to set the array as a global var. Also notice that markers_array is an object that contain all the markers latitudes and longitudes and also other data if you want to initialize an infowindow also.
var markers;
var map;
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
for(i=0;i<markers_array.length;i++){
addMarker(markers_array[i].lat,markers_array[i].long);
}
function addMarker(lat,lng) {
var myLatlng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
map: map,
position: myLatlng,
name: zip
});
markers.push(marker);
}
LATER EDIT:
Here is an example of the marker array in json format:
[
{
"name":"Marker 1 Italy",
"lat":"46.027482",
"long":"11.114502"
},
{
"name":"Marker 2 France",
"lat":"48.019324",
"long":"3.555908"
},
{
"name":"Marker 3 Spain",
"lat":"40.329796",
"long":"-4.595948"
}
]
I am using google maps api to place markers on a map. The gps coordinates of the markers are stored in a mySQL database. I have been able to create the markers however the locations will constantly changing so I was wondering how I would go about updating the markers' locations so that the markers will move across the map. Here is my code so far:
<!DOCTYPE html>
<html>
<head><title>Map</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(36.9947935, -122.0622702);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var image = new google.maps.MarkerImage('busIcon.png',
// The image size
new google.maps.Size(44, 46),
// The origin
new google.maps.Point(0,0),
// The anchor
new google.maps.Point(22, 23));
var shadow = new google.maps.MarkerImage('busIcon_shadow.png',
new google.maps.Size(58, 46),
new google.maps.Point(0,0),
new google.maps.Point(22, 23)
);
var shape = {
coord: [1, 1, 1, 45, 43, 45, 43 , 1],
type: 'poly'
};
var markers = [
<?php
// Make a MySQL Connection
mysql_connect("**********", "**********", "**********") or die(mysql_error());
mysql_select_db("matsallen") or die(mysql_error());
//Get number of rows
$result = mysql_query
(
'SELECT COUNT(*) FROM busTrack AS count'
)
or die(mysql_error());
$row = mysql_fetch_array( $result );
$length = $row["COUNT(*)"];
for ($count = 1; $count <= $length; $count++) {
//Get data from MySQL database
$result = mysql_query
(
'SELECT * FROM busTrack WHERE busID = '.$count
)
or die(mysql_error());
// store the record of the "busTrack" table into $row
$row = mysql_fetch_array( $result );
// Echo the data into the array 'markers'
$output = '{id: "Bus '.$row[busID].'", lat: '.$row[lat].', lng: '.$row[lon].'}';
if ($count != $length) {
$output = $output.',';
};
echo $output;
};
?>
];
for (index in markers) addMarker(map, markers[index]);
function addMarker(map, data) {
//create the markers
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.id,
icon: image,
shape: shape,
shadow: shadow
});
//create the info windows
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.id;
content.appendChild(title);
var infowindow = new google.maps.InfoWindow({
content: content
});
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:75%; height:75%; margin:10%; allign:center;"></div>
</body>
</html>
To change the location of a marker, call setPosition() on that marker:
marker.setPosition(new google.maps.LatLng(newLat,newLng);
To do this, you will need to save all your markers in an array. Perhaps something like this would work:
var myMarkers = new Array();
for (index in markers) {
myMarker[ markers[index]['id'] ] = addMarker(map, markers[index]);
}
function addMarker(map, data) {
//create the markers
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.id,
icon: image,
shape: shape,
shadow: shadow
});
//create the info windows
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.id;
content.appendChild(title);
var infowindow = new google.maps.InfoWindow({
content: content
});
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
return marker;
}
Then, when the position of a marker needs to change, hopefully you know the bus ID and can just call:
myMarkers['Bus 47'].setPosition(new google.maps.LatLng(newLat,newLng);
I didn't test the above code so there may be small syntax errors or something, but it should give you the idea.