In my code I want to parse JSON data and show Google Maps info windows but When I convert through JSON.parse() function and pass it as variable info Maps info windows won't work properly, but when I use JSON.parse function to convert and display result in textarea then put converted values manually it shows info windows properly
Here is what I return through AJAX/JSON Raw
[
"['<div class=\"info_content\"><h3>test 1<\/h3><h4>Contact: 33<\/h4><p>33<\/p><\/div>']",
"['<div class=\"info_content\"><h3>test 2<\/h3><h4>Contact: 22<\/h4><p>22<\/p><\/div>']",
"['<div class=\"info_content\"><h3>test 3<\/h3><h4>Contact: 55<\/h4><p>55<\/p><\/div>']"
]
This is what I require to display infowindows
[
['<div class="info_content"><h3>test 1</h3><h4>Contact: 33</h4><p>33</p></div>'],
['<div class="info_content"><h3>test 2</h3><h4>Contact: 22</h4><p>22</p></div>'],
['<div class="info_content"><h3>test 3</h3><h4>Contact: 55</h4><p>55</p></div>']
]
This is my JS Part which making problem
//Ajax Success response
var location_box = JSON.parse(response);
var infoWindowContent = location_box;
// Add multiple markers to map
var infoWindow = new google.maps.InfoWindow(), marker, i;
Complete JS Code
<script>
var markers = [];
function initMap(location_data, location_box) {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap',
center: new google.maps.LatLng(54.57951, -4.41387),
};
// Display a map on the web page
map = new google.maps.Map(document.getElementById("map"), mapOptions);
map.setTilt(50);
// Multiple markers location, latitude, and longitude
//alert(location_data);
var markers = location_data;
//var markers = [['test 1', 25.1212, 55.1535, 5],['test 2', 25.2084, 55.2719, 6],['test 3', 25.2285, 55.3273, 7]];
var infoWindowContent = location_box;
// Add multiple markers to map
var infoWindow = new google.maps.InfoWindow(),
marker, i;
// Place each marker on the map
for (i = 0; i < markers.length; i++) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Add info window to marker
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Center the map to fit all markers on the screen
map.fitBounds(bounds);
}
// Set zoom level
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(15);
google.maps.event.removeListener(boundsListener);
});
}
$(document).ready(function() {
var location_data;
$("#mapped").on("change", function() {
var dataname = $(".selectpicker option:selected").val();
$.ajax({
url: "findforwork.php",
type: "POST",
data: "searchid=" + dataname,
success: function(response) {
//alert('Success' + response);
var str_response = response;
var res_new = str_response.split("==============");
var location_data = JSON.parse(res_new[0].replace(/\"/g, "").replace(/\'/g, "\""));
var location_box = res_new[1]; // Info windows Array will be here
$('#infoBx').val(location_box);
var mapDiv = document.getElementById('map');
google.maps.event.addDomListener(mapDiv, "load", initMap(location_data, location_box));
}
}); //End Of Ajax
}); //End of mapped
});
</script>
PHP Code to generate JSON data
$locations = array();
$locas = array();
$infoDialog = array();
if (is_numeric($_POST['searchid'])) {
$service_id = $_POST['searchid'];
$query = "SELECT * FROM tblemployees WHERE FIND_IN_SET($service_id, service)";
if (!$result = mysqli_query($conn, $query)) {
exit(mysqli_error($conn));
}
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
// username is already exist
$print_info = null;
$latitude = $row['ltd'];
$longitude = $row['lotd'];
$person_name = $row['fullname'];
$person_id = $row['id'];
$person_contact = $row['contact'];
$person_address = $row['address'];
$locations[] = array(
'name' => $person_name,
'lat' => $latitude,
'lng' => $longitude,
'lnk' => $person_id
);
$locas[] = "['" . $person_name . "', " . $latitude . ", " . $longitude . ", " . $person_id . "]";
$print_info .= '<div class="info_content">';
$print_info .= '<h3>' . $person_name . '</h3>';
$print_info .= '<h4>Contact: ' . $person_contact . '</h4>';
$print_info .= '<p>' . $person_address . '</p>';
$print_info .= '</div>';
$infoDialog[] = "['" . $print_info . "']";
}
}
$json_response = json_encode($locas);
$json_info = json_encode($infoDialog);
echo $json_response . "==============" . $json_info;
}
It´s not clear if response is an array or a string. If it is a array of strings, you should parse each member, such:
var location_box = response.map(x=>JSON.parse(x));
This way location_box will be an array of one element arrays.
EDIT:
By your code, the response var is a string, so, first parse it:
var location_box = JSON.parse(res_new[0]).map(x=>JSON.parse(x));
Related
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 am working with google map api, I maintain separate database(mysql) which contains location(address & latlng), when I call a single location it works, but when there is more than one location to put a marker on the map, the google dev tool says uncaught Range error: maximum call stack size exceeded. I've tried all the sources in the interweb, all the results are negative.
$(document).ready(function(){
$("#searchbutton").click(function(){
var category = document.getElementById("categoryinput").value;
var place = document.getElementById("placeinput").value;
$("#mapcontainer").css("display","block");
$.get("http://localhost:80/rule/search.php?category="+category+"&place="+place, function(data){
$("#hiddeninput").val(data);
//Initialize the Google Maps
var geocoder;
var map;
var markersArray = [];
var infos = [];
geocoder = new google.maps.Geocoder();
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 9
};
//Load the Map into the map_canvas div
var map = new google.maps.Map(document.getElementById("mapcontainer"), myOptions);
map = new google.maps.Map(document.getElementById("mapcontainer"), myOptions);
//Initialize a variable that the auto-size the map to whatever you are plotting
var bounds = new google.maps.LatLngBounds();
//Initialize the encoded string
var encodedString;
//Initialize the array that will hold the contents of the split string
var stringArray = [];
//Get the value of the encoded string from the hidden input
encodedString = document.getElementById("hiddeninput").value;
//Split the encoded string into an array the separates each location
stringArray = encodedString.split("****");
var x;
for (x = 0; x < stringArray.length; x = x + 1)
{
var addressDetails = [];
var markericon = 'img/mapmarker.png';
var marker;
//Separate each field
addressDetails = stringArray[x].split("&&&");
//Load the lat, long data
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
//Create a new marker and info window
marker = new google.maps.Marker({
map: map,
position: lat,
animation: google.maps.Animation.DROP,
//Content is what will show up in the info window
content: addressDetails[0],
icon: markericon
});
//Pushing the markers into an array so that it's easier to manage them
markersArray.push(marker);
google.maps.event.addListener( marker, 'click', function () {
closeInfos();
var info = new google.maps.InfoWindow({content: this.content});
//On click the map will load the info window
info.open(map,this);
infos[0]=info;
});
//Extends the boundaries of the map to include this new location
bounds.extend(lat);
}
//Takes all the lat, longs in the bounds variable and autosizes the map
map.fitBounds(bounds);
//Manages the info windows
function closeInfos(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}
});
});
});
this code sends the jquery ajax request
<?php
header('Access-Control-Allow-Origin:*');
//create connection to database MYSQL
mysql_connect('localhost','root','');
mysql_select_db('locations') or exit('no db found');
$category = $_GET['category'];
$place = $_GET['place'];
if(empty($category) && empty($place)){
echo "invalid input";
}
else{
$searchquery ="SELECT * FROM `locationDatabase` WHERE `category`='$category'and `nagar`='$place' or `area`='$place'";
$searchqueryexecute = mysql_query($searchquery);
while($rows = mysql_fetch_assoc($searchqueryexecute)) {
# code...
$encodedstring = "";
$x = 0;
if($x == 0){
$seperator = "";
}
else{
$seperator = "****";
}
$encodedstring = $encodedstring.$seperator.
"<p class='info'><b>".$rows['name'].
"</b><br><b>".$rows['door_no'].
"</b><br><b>".$rows['street'].
"</b><br><b>".$rows['nagar'].
"</b><br><b>".$rows['area'].
"</b><br><b>".$rows['city']."-".$rows['zipcode'].
"</b></p>&&&".$rows['latitude']."&&&".$rows['longitude'];
$x = $x + 1;
echo $encodedstring;
}
}
?>
Your code is appending an extra "****" to the end of the data string. That causes an extra empty point to be added to the map, which makes the bounds invalid. Either add error checking before creating the maker:
if (isNaN(addressDetails[1]) || isNaN(addressDetails[2])) {
alert("invalid data point:"+x+" ("+addressDetails[1]+","+addressDetails[2]+")");
continue;
}
Or remove the extra "****" from the end of the data.
Looks like your PHP should be (only echo the string to the output when it is complete):
$encodedstring = "";
$x = 0;
while($rows = mysql_fetch_assoc($searchqueryexecute)) {
# code...
if($x == 0){
$seperator = "";
}
else{
$seperator = "****";
}
$encodedstring = $encodedstring.$seperator.
"<p class='info'><b>".$rows['name'].
"</b><br><b>".$rows['door_no'].
"</b><br><b>".$rows['street'].
"</b><br><b>".$rows['nagar'].
"</b><br><b>".$rows['area'].
"</b><br><b>".$rows['city']."-".$rows['zipcode'].
"</b></p>&&&".$rows['latitude']."&&&".$rows['longitude'];
$x = $x + 1;
}
echo $encodedstring;
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.
I Have a google Map, which gets markers loaded based on a date variable, in the PHP. The default date is current date. Now I want the date to be changeable, through a form. On the page where the map is, I have a form, where users can select a date, and I want the map to reload markers based on the date selected. I have an onChange event call the mytest(); function, which will re-load the map. I can't get it to work, when the date is changed, nothing happens. Here is my code.
JavaScript
function mytest() {
var map = ''
function MyMap(){
var im = 'http://www.robotwoods.com/dev/misc/bluecircle.png';
var CustomMarker = 'http://findmyyard.com/images/MarkerIcon.png';
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(locate);
} else {
alert('Please enable "Location Sharing"')
}
function locate(position){
var myLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
zoom: 12,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
streetViewControl: false,
}
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var userMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: im
});
var infoWindow = new google.maps.InfoWindow;
var date = document.getElementById('finddate').value;
// Change this depending on the name of your PHP file
downloadUrl("phps/xmltest.php"+ date, 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 dt1 = markers[i].getAttribute("date1");
var dt2 = markers[i].getAttribute("date2");
var dt3 = markers[i].getAttribute("date3");
var tm1 = markers[i].getAttribute("time1");
var tm2 = markers[i].getAttribute("time2");
var tm3 = markers[i].getAttribute("time3");
var html = "<b>" + name + "</b> <br/>" + "Date of Yard Sale: " + dt1 + ' ' + tm1 + ' ' + dt2 + ' ' + tm2 + ' ' + dt3 + ' ' + tm3 + ' ' + "<br/>" + address;
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = new google.maps.Marker({
map: map,
position: point,
icon: CustomMarker
});
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, html);
});
}
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() {}
}
}}
PHP - xmltest.php
<?php
$date = $_GET['date'];
if($date == "''" || $date == "Today") { $date = date('m-d-Y');} else {$date = $_GET['date'];}
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a MySQL server
mysql_connect("localhost", "someuser", "somepw");
// Set the active MySQL database
$db_selected = mysql_select_db("Registration2");
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM REGISTERED2 WHERE DateONE = '$date' or DateTWO = '$date' or DateTHREE = '$date'";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name",$row['Name']);
$newnode->setAttribute("address", $row['Address']);
$newnode->setAttribute("lat", $row['Latitude']);
$newnode->setAttribute("lng", $row['Longitude']);
$newnode->setAttribute("date1", $row['DateONE']);
$newnode->setAttribute("date2", $row['DateTWO']);
$newnode->setAttribute("date3", $row['DateTHREE']);
$newnode->setAttribute("time1", $row['TimeONE']);
$newnode->setAttribute("time2", $row['TimeTWO']);
$newnode->setAttribute("time3", $row['TimeTHREE']);
}
echo $dom->saveXML();
?>
Please help me out and let me know what I'm doing wrong.
All I needed to do was change the name of var "Date" to something else.
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.