Update Markers Position every X time - google-maps

I`m trying to Update markers position every X time and wonder what is the best way to do that and if there is good example for it.
my code is:
<?php
include 'connect.php';
$json= array();
$res = "SELECT LatLon,fname FROM customers";
$res = mysql_query($res);
while($r = mysql_fetch_assoc($res)) {
$XY = explode(",",$r['LatLon']);
$json[]= array($r['fname'],$XY[1],$XY[0]);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var map;
// Cretes the map
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
// This function takes an array argument containing a list of marker data
function generateMarkers(locations) {
for (var i = 0; i < locations.length; i++) {
new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
title: locations[i][0]
});
}
}
</script>
</head>
<body>
<div id="map" style="width: 1000px; height: 700px;"></div>
<script type="text/javascript">
window.onload = function () {
initialize();
var locations = <?php echo json_encode($json); ?>;
//setInterval(function(){generateMarkers(locations);},1000);
generateMarkers(locations);
};
</script>
</body>
</html>
I need to put the data in other file? if yes how to do that? and how I can make the refresh only on the markers and not on the page.
any suggestions?
thanks!

Using JQuery $.ajax();
index.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
var map;
// Cretes the map
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
// This function takes an array argument containing a list of marker data
function generateMarkers(locations) {
for (var i = 0; i < locations.length; i++) {
new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
title: locations[i][0]
});
}
}
</script>
</head>
<body>
<div id="map" style="width: 1000px; height: 700px;"></div>
<script type="text/javascript">
window.onload = function () {
initialize();
setInterval(function()
{
$.ajax({
url: "http://yoursite.com/location.php",
type: "POST",
data: {func: 'getLocation'},
success: function(data) {
generateMarkers(data);
}
});
}, 1000);
};
</script>
</body>
</html>
location.php:
<?php
include 'connect.php';
if (isset($_POST['func']) && $_POST['func'] === 'getLocation')
{
echo getLocation();
function getLocation()
{
$json= array();
$res = "SELECT LatLon,fname FROM customers";
$res = mysql_query($res);
while($r = mysql_fetch_assoc($res)) {
$XY = explode(",",$r['LatLon']);
$json[]= array($r['fname'],$XY[1],$XY[0]);
}
return $json;
}
}
?>
Try it!

Related

Error in displaying map with direction

I am creating a wp8 application , and I am using this html code to display 2 pushpins and the directions between them but the problem is that the directions are displayed without the map (on the emulater the html page is all displayed without problem).
There is my Html code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Amex</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var rendererOptions = {
draggable: false
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
var map;
var ksa = new google.maps.LatLng(24.7116667, 46.7241667);
function initialize() {
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: ksa
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.directions);
});
calcRoute();
}
function calcRoute() {
var request = {
origin: new google.maps.LatLng(23.7116667, 45.7241667),
destination: new google.maps.LatLng(20.7116667, 45.7241667),
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.
document.getElementById("total").innerHTML = total + " km";
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:80%"></div>
<div id="directionsPanel" style="width:100%;height 20%;font-family:arial">
<p>Total Distance: <span id="total"></span></p>
</div>
</body>
</div>
</body>
</html>
I have find the solution It is just need to replace this
<div id="map_canvas" style="width:100%; height:80%"></div>
by this
<div id="map_canvas" style="width:300px; height:480px"></div>

Google map from address in html

i am try to google load map which get map from address for that i try below code but it not work for me please find out my mistake.
<html>
<head>
<script src="http://maps.google.com/maps/api/js?libraries=places&region=uk&language=en&sensor=true"></script>
<script type="text/javascript">
var geocoder;
var map;
function codeAddress() {
geocoder = new google.maps.Geocoder();
var lat = '';
var lng = '';
var city_state_zip ='390002';
var street_address = 'vadodara';
var address = street_address + " " + city_state_zip;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat(); //getting the lat
lng = results[0].geometry.location.lng(); //getting the lng
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
var latlng = new google.maps.LatLng(lat, lng);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
window.onload = function () {
codeAddress();
}
</script>
</head>
<body>
<div id="map_canvas" style="height: 350px; width: 500px; margin: 0.6em;">
</div>
</body>
</html>
in that there i add location manual which is '390002 vadodara'.
See the Google Maps API here
What you want to do is send an AJAX request like the following:
http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=vadodara+390002
This will return latitude and longitude coordinates for you to plot on the map
Here is a complete solution, the RTN_address.php function is below.
This will return a map that has a marker on the address specified.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=8" / >
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 300px;
width: 840px;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
function show_map_from_sql_address(id) {
var url_with_ID = "RTN_address.php?id=" + id.toString();
$.ajax({
type : "GET",
url : url_with_ID,
data : "pid=A5843",
dataType : "json",
success : function(data) {
var geocoder = new google.maps.Geocoder();
var address = data.foo;
var map;
geocoder.geocode({
'address' : address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom : 10,
center : latlng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map : map,
position : results[0].geometry.location
});
}
});
}
});
};
</script>
</head>
<body onload="show_map_from_sql_address(7)">
<div id="map-canvas"></div>
</body>
</html>
RTN_address.php
<?php
$id = $_GET['id'];
$query1 = "SELECT * FROM table_of_homes WHERE id ='" . $id . "';";
$result1 = mysql_query($query1);
$address = "Not_set";
if (!$result1) {
die('Invalid query: ' . mysql_error());
} else {
$fields = array();
while ($row1 = mysql_fetch_array($result1, MYSQL_ASSOC)) {
$Street_Address = $row1['Street_Address'];
$City_Town = $row1['City_Town'];
$State = $row1['State']`enter code here`;
$Zipcode = $row1['Zipcode'];
$address = $Street_Address ." ". $City_Town ." ". $State .", ". $Zipcode;
}
}
//NOTE: you can test this by entering an address here.
//$address = "111 Oak Hill Avenue Kingston PA, 18760";
echo json_encode(array('foo' => $address ));
?>

Directions for more than one location on Google Maps API v. 3

Using this solution, I was able to successfully map two locations using this source code below. How do I add a third or fourth location as a waypoint in between the beginning and end locations? I tried to add a second end point but that did not work?
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var Center=new google.maps.LatLng(18.210885,-67.140884);
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var properties = {
center:Center,
zoom:20,
mapTypeId:google.maps.MapTypeId.SATELLITE
};
map=new google.maps.Map(document.getElementById("map"), properties);
directionsDisplay.setMap(map);
var marker=new google.maps.Marker({
position:Center,
animation:google.maps.Animation.BOUNCE,
});
marker.setMap(map);
Route();
}
function Route() {
var start = new google.maps.LatLng(18.210885,-67.140884);
var end =new google.maps.LatLng(18.211685,-67.141684);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
} else { alert("couldn't get directions:"+status); }
});
}
google.maps.event.addDomListener(window,'load',initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>
I think, you would be comfortable to use a Polyline.
Try this variant:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Complex polylines</title>
<link rel="stylesheet" type="text/css" href="https://developers.google.com/maps/documentation/javascript/examples/default.css">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var poly;
var map;
function initialize() {
var chicago = new google.maps.LatLng(18.210885,-67.140884);
var mapOptions = {
zoom: 20,
center: chicago,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var lineCoordinates = [
new google.maps.LatLng(18.210885,-67.140884),
new google.maps.LatLng(18.211685,-67.141114),
new google.maps.LatLng(18.211685,-67.141684)
];
var polyOptions = {
path: lineCoordinates,
strokeColor: '#dd4b39',
strokeOpacity: 1.0,
strokeWeight: 5
}
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
for (i = 0; i <= lineCoordinates.length; i++)
{
if (lineCoordinates[i] !== undefined)
{
new google.maps.Marker({
position: lineCoordinates[i],
title: 'some title',
map: map
});
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>

Drop Down Menu (Sidebar)

I've put together the code below to load marker data from my SQL database which correctly shows all of the information held.
I'd like to now include a drop down menu that shows the markers by their 'Location Name' and when the user selects the location the associated marker bounces. I know from some of the information that I've found that this is a sidebar? Could someone perhaps please point me in the right direction as to how I would go about adapting my code to include this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>All Locations</title>
<link rel="stylesheet" href="css/style.css" type="text/css" media="all" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript">
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
zoom:6,
mapTypeId: 'roadmap'
});
// Change this depending on the name of your PHP file
downloadUrl("phpfile.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("locationname");
var address = markers[i].getAttribute("address");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("osgb36lat")),
parseFloat(markers[i].getAttribute("osgb36lon")));
var marker = new google.maps.Marker({
map: map,
position: point,
});
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onLoad="load()">
<div id="map"
</div>
</body>
</html>
UPDATE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Map My Finds - All Locations</title>
<link rel="stylesheet" href="css/alllocationsstyle.css" type="text/css" media="all" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
Location Name
<script type="text/javascript">
var customIcons = {
0: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
1: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
zoom:6,
mapTypeId: 'roadmap'
});
// Change this depending on the name of your PHP file
downloadUrl("mapmyfindsloadalllocations.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var locationname = markers[i].getAttribute("locationname");
var address = markers[i].getAttribute("address");
var finds = markers[i].getAttribute("finds");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("osgb36lat")),
parseFloat(markers[i].getAttribute("osgb36lon")));
var icon = customIcons[finds] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
title: locationname + ' - ' + address,
icon: icon.icon,
shadow: icon.shadow
});
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
<script type="text/javascript">
function animate(element) {
var marker = getMarkerByName(element.title);
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function() { marker.setAnimation(null); }, 200); }
function getMarkerByName(name) {
// retrieve and return the marker from where you stored it }
</script>
</head>
<body onLoad="load()">
<div id="map"></div>
<label></label>
</body>
</html>
Here's an idea:
Associate each location name with the link in the drop down menu.
Store the marker for each location.
When you click a link from the drop down menu, retrieve the marker associated with that location and simply call a function that animates it:
....
<!-- assuming this is an item from the menu -->
Location Name
....
The script:
<script type="text/javascript">
function animate(element) {
var marker = getMarkerByName(element.title);
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function() { marker.setAnimation(null); }, 200);
}
function getMarkerByName(name) {
// retrieve and return the marker from where you stored it
}
</script>
...
Something like that
UPDATE:
There is basically no change... when you click the link, highlight it and call the animate function.
For highlighting the correct link on marker click, "listen" for click on each marker:
google.maps.event.addListener(marker, 'click', function(event) {
// animate marker
// highlight the link associated with the marker.
});

How do I get all coords from a map?

Here is my google maps api project:
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var rio = new google.maps.LatLng(-22.894125,-43.199358);
var map;
function initialize() {
var myOptions = {
zoom: 10,
center: rio,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(marker, 'click', toggleBounce);
}
function addMarkerAtCenter() {
var marker = new google.maps.Marker({
position: map.getCenter(),
draggable:true,
animation: google.maps.Animation.DROP,
map: map
});
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
</script>
</head>
<body onload="initialize()" style="margin:0px; padding:0px;">
<center><input type="button" value="Adicionar Marcador" onclick="addMarkerAtCenter()"/></center>
<center><div id="map_canvas" style="width:100%; height:100%"></div></center>
</body>
how can I, after adding multiple markers, get them and save into xml ?
thanks
I am pretty sure that it doesn't work that way. Markers know what map they belong to, but not the other way around. The way you would normally do this would be to have an Array, and each time you add a marker to your map you also add it to your array. Whenever you want to manipulate your markers you then run through that array and do the stuff that needs doing :)
What you are probably after (if you outputing stuff to XML) is just the coordinates of each marker added rather than the whole google marker object below is an example of how to get the coordinates and serialize them (badly) to XML.
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var rio = new google.maps.LatLng(-22.894125,-43.199358);
var map;
//you probably just want to store coordinates of markers
var coords = []
function initialize() {
var myOptions = {
zoom: 10,
center: rio,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// google.maps.event.addListener(marker, 'click', toggleBounce);
}
function addMarkerAtCenter() {
var marker = new google.maps.Marker({
position: map.getCenter(),
draggable:true,
animation: google.maps.Animation.DROP,
map: map
});
//get the coordinates of the marker
pos = marker.getPosition();
//save the coordinates
coords.push({lat:pos.lat(), lng:pos.lng()})
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
//a primitive serialize function - add something more sophisticated
function serialize(arr) {
xml = "<markers>";
for (i=0;i<arr.length;i++) {
xml += "<marker>";
for(var prop in arr[i]) {
if(arr[i].hasOwnProperty(prop))
xml += "<" + prop +">" + arr[i][prop] + "</" + prop +">";
}
xml += "</marker>";
}
xml +="</markers>";
//do something with the result
alert(xml);
}
</script>
</head>
<body onload="initialize()" style="margin:0px; padding:0px;">
<center><input type="button" value="Adicionar Marcador" onclick="addMarkerAtCenter()"/> <input type=button onClick="javascript:serialize(coords)" value="To XML"></center>
<center><div id="map_canvas" style="width:100%; height:100%"></div></center>
</body>