Show Markers (from database) if along a Google Directions route - javascript

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.

Related

JSON parse won't convert into Array

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));

updated the position of the marker but the previous one is still displayed in google maps api

I am quite new to google maps api and I updated the coordinates of my marker via ajax. I wanted the marker to like, move, but instead it's like generating a new one with the new coordinate and the previous one is still there. How can I remove the old marker when I update my marker with a new coordinate?
maps.html
<!DOCTYPE html>
<html>
<head>
<style>
#map {
width: 800px;
height: 600px;
}
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v=3&
amp;key=AIzaSyDh0-6mPaP9RezyUZkrv2uqX8BGh3nzFCM"></script>
<script src="maps.js"></script>
</head>
<body>
<div id="map"></div>
</body>
</html>
maps.js
function initialize() {
// Create a map object and specify the DOM element for display.
var mapCanvas = document.getElementById('map');
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions)
setInterval(function(){
requestLatLng('getlatlng.php', function(data){
var data = JSON.parse(data.responseText);
displayMarker(data);
//alert(parseFloat(data.latitude) + " " + parseFloat(data.longitude))
console.log(parseFloat(data.latitude) + " " + parseFloat(data.longitude));
map.setCenter(new google.maps.LatLng(parseFloat(data.latitude), parseFloat(data.longitude)));
});
}, 3000);
var gmarkers = [];
var marker;
function displayMarker(data){
var myLatLng = {lat: parseFloat(data.latitude), lng: parseFloat(data.longitude)};
var title = data.name + ", " + data.country;
marker = new google.maps.Marker({
map: map,
position: myLatLng,
title: title
});
if(gmarkers.length < 1){
gmarkers.push(marker);
}
console.log(gmarkers.length);
//console.log("x: " + gmarkers[0].tg.xa.x + "\ny: "+ gmarkers[0].tg.xa.y)
}
}
function requestLatLng(url, callback){
var request;
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}else{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200){
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
google.maps.event.addDomListener(window, 'load', initialize);
getlatlng.php
<?php
header('Content-type: application/json');
define('HOST', 'localhost'); // The host you want to connect to.
define('USER', 'root'); // The database username.
define('PASSWORD', ''); // The database password.
define('DATABASE', 'rummage'); // The database name.
global $conn;
// Check connection
try{
$conn = new PDO('mysql:host = '.HOST.';dbname='.DATABASE, USER, PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'Connected successfully';
}catch (PDOException $e) {
echo "Connection failed " . $e->getMessage();
}
$id = 21;
$query = $conn->prepare("SELECT * FROM regions where id = ?");
$query->execute(array($id));
while($row = $query->fetch()){
$rows[] = $row;
}
foreach ($rows as $roww) {
echo json_encode($roww);
}
?>
this is the json output of my getlatlng.php file:
{"id":"19","0":"19","country":"AF","1":"AF","code":"06","2":"06","name":"Farah\r","3":"Farah\r","latitude":"32.3754","4":"32.3754","longitude":"62.1123","5":"62.1123","cities":"0","6":"0"}
In your displayMarker() function, try this at the beginning:
if (marker) {
marker.setMap(null);
marker = null;
}
I would recommend you to check this article:
Building a Google Maps Application with Updating Markers
He uses arrays in html to have all the saved markers and then update them. In case of a new one he just creates it and puts it in the list.
EDIT:
This is how I did it:
//Used to remember markers
var markerStore = {};
//Time between marker refreshes
var INTERVAL = 250;
function getMarkers() {
$.ajax({
type: 'GET',
url: 'webresources/mobile/retrieve-position',
contentType: 'application/json',
dataType: "json", //linea fragril
beforeSend: function (xhr) {
// Set the CSRF Token in the header for security
var token = window.sessionStorage.accessToken;
if (token) {
xhr.setRequestHeader('userToken', token);
}
else {
xhr.abort();
}
},
success: function (res, textStatus, jqXHR) {
if (jqXHR.status !== 204) {
for (var i = 0; i < res.length; i++) {
if (markerStore.hasOwnProperty(res[i].username)) {
//Check if marker is still alive
if(res[i].alive){
Destroy the marker
markerStore[res[i].username].setMap(null);
}
else{
Change markers position reading the new marker information.
markerStore[res[i].username].setPosition(new google.maps.LatLng(res[i].lat, res[i].long));
}
}
else {
//If it doesnt exist, create a new one.
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + res[i].color);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(res[i].lat, res[i].long),
title: res[i].username,
icon: pinImage,
map: map
});
markerStore[res[i].username] = marker;
console.log(marker.getTitle());
}
}
window.setTimeout(getMarkers, INTERVAL);
}
},
error: function () {
console.log("Error loading markers.");
}
});
}

show route by road between multiple locations on a google map [duplicate]

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.

ajax request xml from php

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.

how to link sidebar to the markers

I am trying to add sidebar. I am using name variable for links on the sidebar which are fetched from the database and it is available to me as an array. I am not able to loop twice as that puts QUERY_LIMIT to the google database.
Can anybody provide me logic on the way how to work on this functionality?
Here is my script:
<script type="text/javascript">
var markers = [];
var side_html = "";
var icon1 = "prop.png";
var icon2 = "office.png";
var locations = <?php echo $add_js ?>;
var name = <?php echo $name_js ?>
//function that will be used to handle clicks on the links in the sidebar
function myclick(num) {
google.maps.event.trigger(locations[num], "click");
}
function geocodeAddress(i)
{
geocoder.geocode({'address' : locations[i]},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
createMarker(results[0].geometry.location, i);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function createMarker(latlng,i) {
var marker = new google.maps.Marker({
map : map,
icon : icon1,
position : latlng
});
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150,50),
disableAutoPan: true
});
google.maps.event.addListener(marker, 'mouseover', function() {
marker.setIcon(icon2);
infowindow.setContent(locations[i]);
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'mouseout', function() {
marker.setIcon(icon1);
infowindow.setContent(locations[i]);
infowindow.close(map, marker);
});
return marker;
}
var map = new google.maps.Map(document.getElementById('map'), {
zoom : 10,
center : new google.maps.LatLng(28.6139, 77.2089),
mapTypeId : google.maps.MapTypeId.ROADMAP
});
//var infowindow = new google.maps.InfoWindow({size: new google.maps.Size(150,50)});
var geocoder = new google.maps.Geocoder();
for (var i = 0 ; i < locations.length; i++) {
geocodeAddress(i);
// link to the sidebar HTML that will open the info window for the record being processed
side_html += '' + name + '<br />';
document.getElementById("side_bar").innerHTML = side_html;
}//end of for loop
</script>
I am getting proper markers in the output, but as the sidebar links i am getting whole of the name array each time and the link is not responding even to click events.
if "name" is an array, this should work:
for (var i = 0 ; i < locations.length; i++) {
geocodeAddress(i);
// link to the sidebar HTML that will open the info window for the record being processed
side_html += '' + name[i] + '<br />';
}//end of for loop
document.getElementById("side_bar").innerHTML = side_html;
Solved my problem at last!
I needed to split my array of strings first before using them to display in the sidebar link.
var name = names[i].split(",");
Final Soltion code:
for (var i = 0 ; i < locations.length; i++)
{
geocodeAddress(i);
var name = names[i].split(",");
side_html += '' + name + '<br />';
}
document.getElementById("side_bar").innerHTML = side_html;

Categories

Resources