This question already has an answer here:
Inconsistent behaviour drawing a route between two points in Google Maps v3
(1 answer)
Closed 8 years ago.
I have a code to show the route between multiple locations on a google map.
It is a using a polyline. However, for the return route to the destination it shows 'as the crow flies'.
I am not using a google API key. Do I need to be? How do I use it if I do? Could this be causing the issue?
I've tried the answer from the link suggested and it doesn't work all the time.
I would have thought this would be a fairly common question - how to plot multiple locations using php.
I've been working on it for a while now and I can't find a solution. How do I get it to stop showing the return route as the crow flies but only ON THE ROAD?
The code I have is:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map = null;
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var markers = [
<?php
// loop through the rows of data
if( have_rows('tour_site', $ID) ):
$info_places = array();
$info_all_places = array();
while( have_rows('tour_site', $ID) ) : the_row();
//display a sub field value
$name = get_sub_field('name');
$long = get_sub_field('long');
$lat = get_sub_field('lat');
$info_places = array("name" => $name, "long"=>$long, "lat"=>$lat);
$info_all_places = array($info_places);
foreach ($info_all_places as $info) {
?>
{
"title": <?php echo "'" . $info['name'] . "'"; ?>,
"lat": <?php echo "'" . $info['lat'] . "'"; ?>,
"lng": <?php echo "'" . $info['long'] . "'"; ?>,
},
<?php
}
endwhile;
else :
endif;
?>
{
"title": 'XXX',
"lat": 'XXX',
"lng": 'XXX',
}
];
</script>
<!-- <script src="//www.gmodules.com/ig/ifr?url=http://hosting.gmodules.com/ig/gadgets/file/114281111391296844949/driving-directions.xml&up_fromLocation=xxx&up_myLocations=<?php echo $destination; ?>&up_defaultDirectionsType=&up_autoExpand=&synd=open&w=320&h=55&title=Directions+by+Google+Maps&lang=en&country=US&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script> -->
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(
parseFloat(markers[0].lat),
parseFloat(markers[0].lng)),
zoom:15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var path = new google.maps.MVCArray();
var service = new google.maps.DirectionsService();
var infoWindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById("map"), mapOptions);
var poly = new google.maps.Polyline({
map: map,
strokeColor: '#F3443C'
});
var lat_lng = new Array();
var marker = new google.maps.Marker({
position:map.getCenter(),
map:map,
title:markers[0].title
});
bounds.extend(marker.getPosition());
google.maps.event.addListener(marker, "click", function(evt) {
infowindow.setContent(this.get('title'));
infowindow.open(map,marker);
});
for (var i = 0; i < markers.length; i++) {
if ((i + 1) < markers.length) {
var src = new google.maps.LatLng(parseFloat(markers[i].lat),
parseFloat(markers[i].lng));
var smarker = new google.maps.Marker({position:des,
map:map,
title:markers[i].title
});
google.maps.event.addListener(smarker, "click", function(evt) {
infowindow.setContent(this.get('title'));
infowindow.open(map,this);
});
var des = new google.maps.LatLng(parseFloat(markers[i+1].lat),
parseFloat(markers[i+1].lng));
var dmarker = new google.maps.Marker({position:des,
map:map,
title:markers[i+1].title
});
bounds.extend(dmarker.getPosition());
google.maps.event.addListener(dmarker, "click", function(evt) {
infowindow.setContent(this.get('title'));
infowindow.open(map,this);
});
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
poly.setPath(path);
map.fitBounds(bounds);
}
});
}
}
}
google.maps.event.addDomListener(window,'load',initialize);
</script>
<div id="dvMap" style="width: 600px; height: 450px"> </div>
Check the returned status parameter google.maps.DirectionsStatus.
It might give you an indication for the problem.
If you get OVER_QUERY_LIMIT you should put a delay between the directions service calls or call it only once with an array that contains up to 10 waypoints.
Read more here.
Related
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$conn = mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("db_jawandsons") or die(mysql_error());
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps</title>
<!-------- Customizable Css for Map ----------------------------->
<style type="text/css">
body { font: normal 10pt Helvetica, Arial; }
#map { width: 1200px; height: 500px; border: 0px; padding: 0px; }
</style>
<!---------------- Java Scripts for Map ----------------->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<!------------- Java Scripts for Map ------------------->
<script type="text/javascript">
var marker;
var map = null;
var markersArray = [];
//--------------------- Sample code written by vIr ------------
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
marker = new google.maps.Marker({
position: pt,
draggable: true,
raiseOnDrag: true,
icon: icon,
map: map
});
markersArray.push(marker);
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN
}
});
setInterval(function mapload(){
$.ajax({
type: "POST",
url: 'location.php',
// data: form_data,
success: function(data)
{
// alert(data);
// var json_obj = $.parseJSON(data);//parse JSON
var json_obj = jQuery.parseJSON(JSON.stringify(data));
for (var i in json_obj)
{ addMarker(json_obj[i].u_lat, json_obj[i].u_lon,"Longitude:" + json_obj[i].u_lon + "<br>" + json_obj[i].u_email + "<br>" + json_obj[i].u_name);
}
},
dataType: "json"//set to JSON
})
},3000);
center = bounds.getCenter();
map.fitBounds(bounds);
}
setInterval(function removeMarker() {
if (markersArray) {
for (i=0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
marker=null;
}
markersArray.length = 0;
}
},3000);
</script>
</head>
<body onLoad="initMap()" style="margin:0px; border:0px; padding:0px;">
<div id="map"></div>
</body>
</html>
It does not add markers to the map.how can i add markers to the map. please anyone tell me where is the problem is, thank in advance :)
<?php
$conn = mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("db_jawandsons") or die(mysql_error());
$return_arr = array();
$data=array();
$result = mysql_query("SELECT lat,lng,vname,speed FROM v_data where sno='1'")or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row['lat'];
$data[] = $row['lng'];
$data[] = $row['vname'];
$data[] = $row['speed'];
//array_push($return_arr,$data);
}
echo json_encode($data);
//echo("addMarker(30.91995, 75.93287, '<b>$name</b><br />$desc');\n");
?>
i want to add my location to the map it will come dynamically. how can i add multiple locations or single location (lat,lon) to the map.
let me know if there is problem in php code. how can i reload the map without page refreash. i tried many scripts but did not work for me. please help me.
Here's what works on me. I have this html page with PHP embedded in it.Maybe you can try to look at and get what you need in here.
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA0XjHka3iMTH5jEuy-bYPWNZdILVOQsWI&callback=initMap"></script>
<script>
function initialize() {
var markers = [];
var mapCanvas = document.getElementById('map-canvas');
//San Pablo City
var myLatlng = new google.maps.LatLng(14.0667, 121.3333);
<?php
if (isset($_GET['latitude']) && $_GET['latitude'] != '' && isset($_GET['longitude']) && $_GET['longitude'] != ''){
?>
myLatlng = new google.maps.LatLng(<?=$_GET['latitude']?>, <?=$_GET['longitude']?>);
<?php } ?>
var mapOptions = {
center: myLatlng,
zoom: 17,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE,google.maps.MapTypeId.HYBRID]
},
mapTypeId: google.maps.MapTypeId.NORMAL
}
var map = new google.maps.Map(mapCanvas, mapOptions);
map.setTilt(45);
var infowindow = new google.maps.InfoWindow({
maxWidth: 400
});
<?php foreach($crimes as $crime) {
if ($crime['latitude'] != null AND $crime['longitude'] != '') {
$content = "<b>Date : ". date('M d Y',strtotime($crime['date_crime']))."</b><br>";
$content .= "<p>". $crime['useful_info']."</p>";
?>
addMarker( new google.maps.LatLng(<?=$crime['latitude']?>,<?=$crime['longitude']?>), '<?=$crime['sub_category']?>','<?=str_replace('#','',$crime['color'])?>','<?=substr($crime['sub_category'],0,1)?>',<?=$crime['complaint_id']?>,<?=esc($content)?>);
<?php } } ?>
addListener();
// Add a marker to the map and push to the array.
function addMarker(location,title,color,letter,id,content) {
var pinColor = color;
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" + letter + "|" + pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
var marker = new google.maps.Marker({
position: location,
map: map,
title : title,
animation: google.maps.Animation.DROP,
icon: pinImage
});
marker.set("id",id);
marker.set("content",content);
markers.push(marker);
}
function getMessage(title,str){
var ret = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h4 id="firstHeading" class="firstHeading">' + title + '</h1>'+
'<div id="bodyContent">'+ str +
'</div>'+
'</div>';
return ret;
}
// Sets the map on all markers in the array.
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setAllMap(null);
}
// Shows any markers currently in the array.
function showMarkers() {
setAllMap(map);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
markers = [];
}
function addListener(){
for (var i = 0; i < markers.length; i++) {
google.maps.event.addListener(markers[i], 'click', function () {
// do something with this marker ...
var id = this.get("id");
infowindow.setContent(getMessage(this.getTitle(),this.get("content")));
infowindow.setPosition(this.getPosition());
infowindow.open(map,markers[i]);
});
}
}
//google.maps.event.addListener(marker, 'click', function() {
// map.setZoom(8);
// map.setCenter(marker.getPosition());
// });
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div class="page-header">
<h3>Report > <small>Map View</small></h2>
</div>
<div class = "col-md-10">
<div id="map-canvas"></div>
</div>
I have problem with my Google Maps API v3 script. I am using CodeIgniter framework.
The problem is when I clicked a marker, and then click another marker, InfoWindow Google Maps on previous marker didn't close. This is my code:
<script type="text/javascript">
var peta;
var gambar_kantor = new Array();
var nama = new Array();
var kategori = new Array();
var alamat = new Array();
var telpon = new Array();
var x = new Array();
var y = new Array();
var i;
var url;
var gambar_marker;
var gambar_kantor;
var baseurl = "<?php echo base_url() ?>";
function map_init() {
var map = new google.maps.LatLng(-6.990411, 110.422542);
var myStyles =[
{
featureType: "poi",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}
];
var petaoption = {
zoom: 12,
center: map,
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: myStyles
};
peta = new google.maps.Map(document.getElementById("map_canvas"),petaoption);
getdatabase();
}
function getdatabase(){
var markers = [];
var info= [];
<?php
$query = $this->db->query("SELECT l.id, l.nama, l.gambar, l.alamat, l.telp, l.latittude, l.longitude, k.nama_kategori, k.ikon
FROM lokasi as l, kategori as k
WHERE l.kategori=k.id");
$i = 0;
$js = "";
foreach ($query->result() as $value) {
$js .= 'nama['.$i.'] = "'.$value->nama.'";
alamat['.$i.'] = "'.$value->alamat.'";
telpon['.$i.'] = "'.$value->telp.'";
x['.$i.'] = "'.$value->latittude.'";
y['.$i.'] = "'.$value->longitude.'";
set_icon("'.$value->ikon.'");
var point = new google.maps.LatLng(parseFloat(x['.$i.']),parseFloat(y['.$i.']));
var contentString = "<table>"+
"<tr>"+
"<td align=center><br><b>" + nama['.$i.'] + "</b></td>"+
"</tr>"+
"<tr>"+
"<td align=center width=300px>" + alamat['.$i.'] + "</td>"+
"</tr>"+
"<tr>"+
"<td align=center> Telp: " + telpon['.$i.'] + "</td>"+
"</tr>"+
"</table>";
var currentInfoWindow = null;
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: point,
map: peta,
icon: gambar_marker,
clickable: true
});
markers.push(marker);
info.push(infowindow);
google.maps.event.addListener(markers['.$i.'], "click", function() {
info['.$i.'].open(peta,markers['.$i.']);
});
';
$i++;
}
// echo JS
echo $js;
?>
}
Any solution to make InfoWindow auto close when another marker clicked?
I have tried several solutions on Stackoverflow and Google but didn't worked. Thanks for your kindly help :)
You could declare just one infowindow, outside of your loop. Then each marker, when clicked, opens that infowindow on itself, filling it with the proper contents.
In the following example I set the contentString property on the marker itself.
var infowindow = new google.maps.InfoWindow();
<?php
foreach ($query->result() as $value) {
....
?>
var marker = new google.maps.Marker({
position: point,
map: peta,
icon: gambar_marker,
clickable: true,
content: contentString
});
markers.push(marker);
google.maps.event.addListener(marker, "click", function() {
infowindow.setContent(marker.content);
infowindow.open(peta,marker);
});
<?php
}
?>
Maybe this link will be of use to you?
Previously answered: Close infowindow when another marker is clicked
Make sure to declare the global variable outside the main google maps code in your JS:
file: var lastOpenedInfoWindow;
Good luck!
i have this code to populate markers from database on google map , but it's is not working ,the xml file is perfectly working , i referred to https://developers.google.com/maps/articles/phpsqlajax_v3, but of no use.
markers.php code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "jainmunilocator";
$connection=mysqli_connect($servername, $username, $password, $dbname);;
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT name,id,lat,lng FROM muni_location,munishri WHERE mid=id";
header('Content-Type: application/xml');
$result=mysqli_query($connection,$sql);
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result)){
if(isset($row['id'])){ $id = $row['id']; }
if(isset($row['name'])){ $name = $row['name']; }
if(isset($row['lat'])){ $lat = $row['lat']; }
if(isset($row['lng'])){ $lng = $row['lng']; }
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("id",$id);
$newnode->setAttribute("name", $name);
$newnode->setAttribute("lat", $lat);
$newnode->setAttribute("lng", $lng);
}
}
echo $dom->saveXML();
?>
*GOOGLE MAP MARKER CODE**
<!DOCTYPE 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>PHP/MySQL & Google Maps Example</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
//<![CDATA[
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(22.6145,77.3418),
zoom: 7,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
var gm_marker = new Array();
// Change this depending on the name of your PHP file
downloadUrl("markers.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("name");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
//var html = "<b>" + name + "</b> <br/>" + id;
var html = name;
var icon = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
var marker = new google.maps.Marker({
map: map,
position: point,
title: name
});
addMarker(point,name);
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
//stackoverflow
function addMarker(latLng, contentstr) {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow = new google.maps.InfoWindow({
content: contentstr
});
});
gm_markers.push(marker);
}
setAllmap(map);
function setAllMap(map) {
for (var i = 0; i < gm_markers.length; i++) {
gm_markers[i].setMap(map);
}
function showMarkers() { setAllMap(map);}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function( ){
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
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-canvas-show" style="width: 100%; height: 300px;"></div>
</body>
</html>
There are 2 elements that I think are essential, which I don't see in your code. This is from my source and I'm including them here to show the concepts. You can implement this type of thing within your for loop or break out into functions. I prefer functions, so I did it this way.
First, I would confirm that your marker array is not length 0--that's an easy sanity check--make sure you have markers to load.
Build the Google Map marker stack
While there are markers...
Create the marker with new
Create the listener with new
Push the marker into Google's marker object as an array of marker objects
// Add a marker to the map and push to the array.
function addMarker(latLng, contentstr) {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow = new google.maps.InfoWindow({
content: contentstr
});
});
gm_markers.push(marker);
}
To show the markers assign the marker to the map
Associate each marker from the array to your map canvas.
// Sets the map on all markers in the array.
function setAllMap(map) {
for (var i = 0; i < gm_markers.length; i++) {
gm_markers[i].setMap(map);
}
To clear the Google Map markers (off)
To reinforce the concept. To clear the markers unplug the map markers object array from your map object.
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setAllMap(null);
}
To show already loaded markers (on)
// Shows any markers currently in the array.
function showMarkers() {
setAllMap(map);
}
In the view
Showing the map with the markers
<div id="map-canvas-show" style="width: 100%; height: 300px;"></div>
Debugging steps (added)
I would suggest first to confirm that valid coordinates are being loaded into the marker vars in your php. In fact, I would start with a test with one single marker. Put in debug statements to show your lat and lng. This is essential. Confirm valid marker data from php into your js.
Then, you need to confirm that those markers are within the visible range of your Google map. Are the markers there, just not visible? To help, I would suggest that you make Google map zoomed way out - scale it so you'd see a marker halfway around the world.
I have a Google Map that displays service stations across mainland Europe and can calculate routes between two locations. However, because there are a lot of stations, the map can look quite busy. I therefore want to only show markers that follow the route my google directions have given.
I thought about tracing the directions with a polyline and perhaps using an intercept, but I can't think of how to talk to the database. My current example shows the directions with an red polyline but with all the markers showing.
The code for the javascript is:
//<![CDATA[
var customIcons = {
as24: {
icon: 'images/as24.png'
},
pearson: {
icon: 'images/p.png'
}
};
var rendererOptions = {
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var map, trafficLayer;
var europe = new google.maps.LatLng(-25.274398, 133.775136);
function initialize() {
var mapOptions = {
zoom: 6,
center: europe
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
var control = document.getElementById('traffic-wpr');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(control);
google.maps.event.addDomListener(control, 'click', function() {
trafficLayer.setMap(trafficLayer.getMap() ? null : map);
});
calcRoute();
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin:start,
destination:end,
//waypoints:[{location: 'London, England'}, {location: 'Paris, France'}],
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
var polyline = new google.maps.Polyline({
path: [],
strokeColor: "#FF0000",
strokeOpacity: 0.2,
strokeWeight: 30,
fillColor: "#FF0000",
fillOpacity: 0.35
});
var bounds = new google.maps.LatLngBounds();
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
var steps = legs[i].steps;
for (j=0;j<steps.length;j++) {
var nextSegment = steps[j].path;
for (k=0;k<nextSegment.length;k++) {
polyline.getPath().push(nextSegment[k]);
bounds.extend(nextSegment[k]);
}
}
}
polyline.setMap(map);
map.fitBounds(bounds);
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.0;
document.getElementById('total').innerHTML = total + ' km';
}
google.maps.event.addDomListener(window, 'load', initialize);
function load() {
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("as24_genxml.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("name");
var address = markers[i].getAttribute("address");
var price = markers[i].getAttribute("price");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + " " + price + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
map.getBounds().contains(marker.getPosition())
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
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() {}
//]]>
The code for the markers (as24_genxml.php) is:
<?php include ('php/config.php');
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $mysql_user, $mysql_pass);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($mysql_db, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM as24 WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'price="' . parseToXML($row['price']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
I can't seem to find anyone else that has a similar problem. I may be overcomplicating things by using the polyline?
Ok, I'm not sure if I'm over-complicating this to be honest but if you merely want the map to look less cluttered then you don't need to change anything in the back-end (presuming you're having no performance issues, I'm unsure how many points we're talking about here. All you need to do is check the distance between each coordinate on the polyline and each 'service station' marker.
An example of how to achieve this is available in the first part of the answer here. You can even hide the polyline to further reduce clutter, or remove it and use the coordinates within each path segment to achieve the same effect.
This could however be an issue if you have a lot of points to check and long routes. The only way to know for sure will be to try it, but the asymptotic complexity is not great.
what i am doing is that i am placing multiple markers on map returned from json array,here is my code.my markers are plotted correctly but when i click on each marker it make info window of one marker that is last marker of array
function latLongCallback(latitutde,longitutde){
var latlng = new google.maps.LatLng(latitutde, longitutde);
var options = {zoom: 4, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById('map'), options);
$.ajax({type: "GET",
dataType: 'json',
url: "http://www.xyz.com/xcv/xainee/test/markers.php",
success: function(response){
var total=response.length;
data_array,name,type,address,lat,lon,point,infowindow,marker,arrival,departure,notes;
var icon_image = 'http://www.xyz.com/userftp/fawad/test/images/map-icon.png';
for(var i=0; i < total; i++)
{
data_array=response[i];
name=data_array['name'];
address=data_array['address'];
arrival=data_array['arrival'];
departure=data_array['departure'];
notes=data_array['notes'];
lat=data_array['lat'];
lon=data_array['lon'];
contentString ="Name : "+name+"<br/> Location : "+address+"<br/> Arrival :"+arrival+"<br/> Departure : "+departure+"<br/> Notes : "+notes;
point = new google.maps.LatLng(lat,lon);
infowindow = new google.maps.InfoWindow({content: contentString,maxWidth: 400,maxHeight: 201});
marker = new google.maps.Marker({map: map,icon: icon_image, position: point});
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() { infowindow.open(map,marker);});
}
}
});
return;
}
here is my markers.php
<?php session_start();
include_once("database.php");
$data=array();
$retrive_marker_query = "SELECT fb_user.name,schedule.location,schedule.arrival,schedule.departure,schedule.notes,schedule.lat,schedule.lon FROM schedule,fb_user where fb_user.fb_id = schedule.fb_id";
$result = db_execute($retrive_marker_query);
$cnt=0;
while ($row = #mysql_fetch_assoc($result)){
$name=$row['name'];
$address= $row['location'];
$arrival= $row['arrival'] ;
$departure= $row['departure'] ;
$notes= $row['notes'] ;
$lat= $row['lat'];
$lon= $row['lon'];
$data[$cnt]['name']=$name;
$data[$cnt]['address']=$address;
$data[$cnt]['arrival']=$arrival;
$data[$cnt]['departure']=$departure;
$data[$cnt]['notes']=$notes;
$data[$cnt]['lat']=$lat;
$data[$cnt]['lon']=$lon;
$cnt++;
}
$data=json_encode($data);
echo($data);
?>
why my markers content are same although all markers are plotted in different lat and lon