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.
Related
Hello I have a file with the next code, a file named google-maps.php
<script>
var customIcons = {
restaurant: {
icon: 'img/homepage/pin.png'
},
cafenele: {
icon: 'img/homepage/pni2.png'
}
};
var markerGroups = {
"restaurant": [],
"cafenele": []
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.059516, 21.947613),
zoom: 13,
scrollwheel: false,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow();
// Change this depending on the name of your PHP file
var bounds = new google.maps.LatLngBounds();
downloadUrl("googlemaps/phpsqlajax_genxml2.php", function (data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var id_marker = markers[i].getAttribute("id_marker");
var name = markers[i].getAttribute("name");
var category = markers[i].getAttribute("category");
var address = markers[i].getAttribute("address");
var img = markers[i].getAttribute("img");
var phone = markers[i].getAttribute("phone");
var schedule = markers[i].getAttribute("schedule");
var link = markers[i].getAttribute("link");
document.getElementById('categorii').src = img;
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
bounds.extend(point);
var html = "<u class='title-google-maps'>" + name + "</u> <p class='google-maps'>" + category + "</p>" + address + "<p class='google-maps'>" + phone + "</p>" + "<p class='google-maps-2'>" + schedule + "</p>" + link;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
id_marker: id_marker,
image: img,
type: type
});
if (!markerGroups[type])
markerGroups[type] = [];
markerGroups[type].push(marker);
marker.setVisible(false);
bindInfoWindow(marker, map, infoWindow, html);
}
map.fitBounds(bounds);
toggleGroup("spa");
});
}
function toggleGroup(type)
{
for (var key in markerGroups)
{
for (var i = 0; i < markerGroups[key].length; i++)
{
var marker = markerGroups[key][i];
if (type == key) {
marker.setVisible(true);
} else
{
marker.setVisible(false);
}
}
}
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(html);
infoWindow.open(map, marker);
document.getElementById('categorii').src = marker.image;
});
}
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>
If I put my code in JS the code works but I need to put in PHP file in future I want to echo some data from database. The error I have in console is Uncaught SyntaxError: Unexpected token< . Why is working if the file type is JS and why is not working on PHP file type? What cand I do?
You need to close php tag before script and open in after script like this
<?php
//some php code
?>
<script>
...
..
</script>
<?php
//php code
?>
Hello i am trying to create a nearest places search form, that generates information that would be displayed on a map based on the locations i have in my database.
i found a very useful tutorial at here https://developers.google.com/maps/articles/phpsqlsearch_v3, and this displays the locations on a map as wanted.
but now i want to take it a step further, and display those information on the map as a list. obviously by echoing the locations, but i have no idea how display them in that way.
this is what i have done
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Google Maps AJAX + mySQL/PHP Example</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var map;
var markers = [];
var infoWindow;
var locationSelect;
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
infoWindow = new google.maps.InfoWindow();
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none"){
google.maps.event.trigger(markers[markerNum], 'click');
}
};
}
function searchLocations() {
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
locationSelect.innerHTML = "";
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
locationSelect.appendChild(option);
}
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'engine.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address);
bounds.extend(latlng);
}
map.fitBounds(bounds);
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(markers[markerNum], 'click');
};
});
}
function createMarker(latlng, name, address) {
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name + "(" + distance.toFixed(1) + ")";
locationSelect.appendChild(option);
}
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.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
//]]>
</script>
</head>
<body style="margin:0px; padding:0px;" onLoad="load()">
<div>
<textarea cols="25" rows="6" id="addressInput"></textarea>
<select id="radiusSelect">
<option value="4" selected>4mi</option>
<option value="100">100mi</option>
<option value="200">200mi</option>
</select>
<input type="button" onClick="searchLocations()" value="Search"/>
</div>
<div><select id="locationSelect" style="width:100%;visibility:hidden"></select></div>
<div id="map" style="width: 100%; height: 80%"></div>
</body>
</html>
and my server side code that does the query
<?php
// Get parameters from URL
$center_lat = $_GET["lat"];
$center_lng = $_GET["lng"];
$radius = $_GET["radius"];
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a mySQL server
$connection=mysql_connect ('localhost', 'root', '');
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db('vitafoam', $connection);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
// Search the rows in the markers table
$query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
mysql_real_escape_string($center_lat),
mysql_real_escape_string($center_lng),
mysql_real_escape_string($center_lat),
mysql_real_escape_string($radius));
$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)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", $row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("distance", $row['distance']);
}
echo $dom->saveXML();
?>
please how can i make this information come out in a list thanks any reply will be useful
Where you're currently looping over the XML marker nodes, amend that to output to a list. I'm not 100% sure what you mean by a list... a <ul />, a textarea, a comma-separated list of addresses, something else?
var list = '';
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
list += name + ', ' + address + ', ' + distance + ';';
}
document.getElementById('yourList').innerHTML = list;
I have a set of markers, and when clicked on a marker there is a button that gets directions. The problem is that it only gives directions to the last loaded marker from the xml, not to each marker individually. Here is my code, maybe someone can tell what I'm doing wrong. Thank you.
UPDATE: WORKING CODE, QUESTION ANSWERED
var map;
var point;
var directionsDisplay;
var directionsService;
var marker;
var myLatLng;
var marklat;
var marklong;
var markers;
var DirLat;
var DirLng;
function loadGoogleMap(){
// load google map
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' +
'callback=MyMap';
document.body.appendChild(script);
}
var map = ''
function MyMap(){
directionsDisplay = new google.maps.DirectionsRenderer();
directionsService = new google.maps.DirectionsService();
var im = //user location icon
var CustomMarker = //marker icon location
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(locate, noPos());
} else {
noPos();
}
function locate(position){
myLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
zoom: 12,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
streetViewControl: false,
mapTypeControl: false,
panControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT},
zoomControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT }
}
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;
downloadUrl("phps/xmltest.php", function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var nam = markers[i].getAttribute("name");
var name = nam.replace('=', '\'');
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 pid = markers[i].getAttribute("PID");
var DirLat = markers[i].getAttribute("lat");
var DirLng = markers[i].getAttribute("lng");
var d = Math.round(Math.random()*1679735965724*236896135089834);
var raw = pid * d;
//move up the creation of point
point = new google.maps.LatLng(
DirLat,
DirLng);
marker = new google.maps.Marker({
map: map,
position: point,
icon: CustomMarker,
id: raw,
id2: d
});
var content = "<button onclick='getDir();'>Get Directions</button>";
var jshtml = "<button onclick='raw();'>More Info</button>"; //an href function that redirects
var html = "<b>" + name + " " + content+ ' ' + jshtml+ "</b> <br/>" + "Date of Yard Sale: " + dt1 + ' ' + tm1 + ' ' + dt2 + ' ' + tm2 + ' ' + dt3 + ' ' + tm3;
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);
center: position;
document.getElementById('iLat').value = marker.getPosition().lat().toFixed(6);
document.getElementById('iLng').value = marker.getPosition().lng().toFixed(6);
document.getElementById('iRaw1').value = marker.id;
document.getElementById('iRaw2').value = marker.id2;
});
}
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();
}
function doNothing() {}
}
function noPos(error){
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(41.850033, -87.6500523),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true,
streetViewControl: false,
mapTypeControl: false,
panControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT},
zoomControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT }
}
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phps/xmltest.php", function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var nam = markers[i].getAttribute("name");
var name = nam.replace('=', '\'');
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 pid = markers[i].getAttribute("PID");
var d = Math.round(Math.random()*1679735965724*236896135089834);
var raw = pid * d;
var jshtml = "<button onclick='raw();'>More Info</button>";;
var html = "<b>" + name + ' ' + jshtml + "</b>" + "<br>" + "Date of Yard Sale: " + dt1 + ' ' + tm1 + ' ' + dt2 + ' ' + tm2 + ' ' + dt3 + ' ' + tm3;
point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
marker = new google.maps.Marker({
map: map,
position: point,
icon: CustomMarker,
id: raw,
id2: d
});
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);
position = marker.position;
center: position;
document.getElementById('iRaw1').value = marker.id;
document.getElementById('iRaw2').value = marker.id2;
});
}
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() {}
}
}
function getDir(){
directionsDisplay.setMap(map);
var start = myLatLng;
//LatLng created based on the passed arguments
var end = point;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
I globally defined every variable necessary for directions:
var map;
var point;
var directionsDisplay;
var directionsService;
var marker;
var myLatLng;
var marklat;
var marklong;
var markers;
var DirLat;
var DirLng;
created a button for the function, and set in content which is visible in the infowindow:
var content = "<button onclick='getDir();'>Get Directions</button>";
Next I created hidden input fields in the map page, and assigned values of Latitude and Longitude of the markers that are clicked.
document.getElementById('iLat').value = marker.getPosition().lat().toFixed(6);
document.getElementById('iLng').value = marker.getPosition().lng().toFixed(6);
The directions function getDir pulls these values for the destination, myLatLng is the current location of the user:
function getDir(){
directionsDisplay.setMap(map);
var start = myLatLng;
var LatDir = document.getElementById('iLat').value;
var LngDir = document.getElementById('iLng').value;
var end = new google.maps.LatLng(LatDir,LngDir);
var request = {
origin:myLatLng,
destination:new google.maps.LatLng(LatDir,LngDir),
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
For the full code, see the updated question's code.
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.
function popupDirections(marker) {
var infowindow = new google.maps.InfoWindow(
{
content:
'Hello World'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
I write this function in order to show the information of place name, street number, or somethings else, but the problem is that I don't know how to get that information to display on the pop up. Any help would be appreciated.
may be you want to try this, this my code that have a element info windows from JSON. but if you only want to write your infowindow, just write it like as tag javascript. in my case, my element of info window, i get from database.
function initialize(){
var x = new Array();
var y = new Array();
var customer_name = new Array();
var cp_rayon_name = new Array();
var icon = new Array();
var photo = new Array();
var city = new Array();
var address = new Array();
var postal_code = new Array();
// posisi default peta saat diload
var petaoption = {
zoom: 5,
center: new google.maps.LatLng( -1.2653859,116.83119999999997),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var peta = new google.maps.Map(document.getElementById("map_canvas"),petaoption);
//bound
var allowedBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(7.449624,93.15033),
new google.maps.LatLng(-12.640338,144.830017)
);
var boundLimits = {
maxLat : allowedBounds.getNorthEast().lat(),
maxLng : allowedBounds.getNorthEast().lng(),
minLat : allowedBounds.getSouthWest().lat(),
minLng : allowedBounds.getSouthWest().lng()
};
var lastValidCenter = peta.getCenter();
var newLat, newLng;
google.maps.event.addListener(peta, 'center_changed', function() {
center = peta.getCenter();
if (allowedBounds.contains(center)) {
// still within valid bounds, so save the last valid position
lastValidCenter = peta.getCenter();
return;
}
newLat = lastValidCenter.lat();
newLng = lastValidCenter.lng();
if(center.lng() > boundLimits.minLng && center.lng() < boundLimits.maxLng){
newLng = center.lng();
}
if(center.lat() > boundLimits.minLat && center.lat() < boundLimits.maxLat){
newLat = center.lat();
}
peta.panTo(new google.maps.LatLng(newLat, newLng));
});
var infowindow = new google.maps.InfoWindow({
content: ''
});
// memanggil function untuk menampilkan koordinat
url = "json.php";
$.ajax({
url: url,
dataType: 'json',
cache: false,
success: function(msg){
for(i=0;i<msg.enseval.customer.length;i++){
x[i] = msg.enseval.customer[i].x;
y[i] = msg.enseval.customer[i].y;
customer_name[i] = msg.enseval.customer[i].nama_customer;
cp_rayon_name[i] = msg.enseval.customer[i].nama_rayon;
icon[i] = msg.enseval.customer[i].icon;
photo[i] = msg.enseval.customer[i].id_photo;
city[i] = msg.enseval.customer[i].city;
address[i] = msg.enseval.customer[i].address;
postal_code[i] = msg.enseval.customer[i].postal_code;
var point = new google.maps.LatLng(parseFloat(msg.enseval.customer[i].x),parseFloat(msg.enseval.customer[i].y));
var gambar_tanda = 'assets/images/'+msg.enseval.customer[i].icon+'.png';
var photo_cust ='<img src="assets/images/foto_cust/'+msg.enseval.customer[i].id_photo+'_1.jpg" style="width:200px;height:120px;"/>';
//var nm_cust = msg.enseval.customer[i].nama_customer;
//var nm_rayon = , msg.enseval.customer[i].nama_rayon;
var html = '<b>' + customer_name[i] + '</b><br/>'+city[i]+ ', '+address[i]+', '+postal_code[i]+'<br/>' + cp_rayon_name[i] + '<br/>' + photo_cust;
tanda = new google.maps.Marker({
position: point,
map: peta,
icon: gambar_tanda,
clickable: true
});
bindInfoWindow(tanda, peta, infowindow, html );
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function bindInfoWindow(tanda, peta, infowindow, data) {
google.maps.event.addListener(tanda, 'click', function() {
infowindow.setContent(data);
infowindow.open(peta, tanda);
});
}
function reload(form){
var val=form.org_id.options[form.org_id.options.selectedIndex].value;
self.location='main_page_admin.php?cabang=' + val ;
}