Google maps, PHP - php

I am fairly new to php and have not figured out how I would perform a certain task.
My code has the user input their address and then choose radius to
search, after they search a map is generated that shows the 3 closest
locations to their address.
I want to make it so that when the user clicks on the marker from the
map it generates a page for that item clicked. saying you clicked on
"store name". Could you please help me understand how this could be
done? Thank you.
<?php
require("phpsqlsearch_dbinfo.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', $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $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 , 3",
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();
?>
and
<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 = 'phpsqlsearch_genxml.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>
<input type="text" id="addressInput" size="10"/>
<select id="radiusSelect">
<option value="3" selected>3mi</option>
<option value="5">5mi</option>
<option value="10">10mi</option>
<option value="25">25mi</option>
</select>
<input type="button" onclick="searchLocations();" value="Search"/>
</div>
<div><select id="locationSelect" style="width:500;visibility:hidden"></select></div>
<div id="map" style="width: 500; height: 500"></div>
</body>
</html>

In JS exist a global variable location. By changing the href attribute you can force the browser to open another url. docu: http://www.w3schools.com/jsref/obj_location.asp
If you need information about the clicked marker you can put this information in a closure scope, to reuse it later when the marker is clicked. The create-function is called on runtime and the returned anonymous function is called by the click event.
Pseudocode:
function createCLickCallback(marker) {
return function () {
var position = marker.getPosition();
location.href = "locationInfo.php?lat=" + position.lat() + "&lng=" + position.lng();
};
}
google.maps.event.addListener(marker, 'click', createCLickCallback(marker));

in your JS function "createMarker" you are adding listener to marker click event:
google.maps.event.addListener(marker, 'click', function() {
...
});
you should add your "page generation" code (whatever it is either open new page or update some part of current page) inside event callback function. In your current code google infowindow will be opened over your marker.

Related

How to load markers from XML file in Google Maps

i have a problem with showing my XML File in my Google Maps
My Concept : MySQL -> XML -> Show To GMaps
Here's My Code :
Index.php
<!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>ODP Tracking</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
var customIcons = {
FTTH: {
icon:"/images/ico_tag.png"
},
MSAN: {
icon:"/images/ico_tag_ms.png"
},
DSLAM: {
icon:"/images/ico_tag_ds.png"
},
bar: {
icon:'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(load);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function updateMarkerPosition(latLng) {
document.getElementById('latitude').value = [latLng.lat()]
document.getElementById('longitude').value = [latLng.lng()]
}
function load(position) {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
zoom: 17,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
var latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var url = "phpsqlajax_genxml.php";
var marker2 = new google.maps.Marker({
position : latLng,
title : 'Lokasi',
map : map,
draggable : false
});
// Change this depending on the name of your PHP file
downloadUrl(url, 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 kap = markers[i].getAttribute("kap");
var avai = markers[i].getAttribute("avai");
var type = markers[i].getAttribute("type");
var note = markers[i].getAttribute("ket");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lang")));
var html = "<b>" + name + "</b> <br/>ALPRO : " + type + "<br/>KAP : " + kap + "<br/>AVAI : " + avai + "<br/>KETERANGAN : " + ket ;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, marker2, map, infoWindow, html);
}
});
updateMarkerPosition(latLng);
google.maps.event.addListener(marker2, 'drag', function() {
updateMarkerPosition(marker2.getPosition());
});
}
function bindInfoWindow(marker, marker2, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker, marker2);
});
}
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="getLocation()">
<style>
html, body, #map {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#map {
position: relative;
}
</style>
<div id="map"></div>
</body>
</html>
and here's my XML Parsing Code
phpsqlajax_genxml.php
<?php
require("phpsqlajax_dbinfo.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
$xmlStr=str_replace("-",'-',$xmlStr);
$xmlStr=str_replace("/",'/',$xmlStr);
return $xmlStr;
}
// Create connection
$conn = new mysqli('localhost', $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
// Select all the rows in the markers table
$sql = "SELECT * FROM koordinat_odp";
$result = $conn->query($sql);
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 = $result->fetch_assoc()){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['nama_dp']) . '" ';
echo 'kap="' . $row['kap'] . '" ';
echo 'avai="' . $row['avai'] . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lang="' . $row['lang'] . '" ';
echo 'type="' . $row['jenis_alpro'] . '" ';
echo 'ket="' . $row['note'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
My Problem : It not showing marker on the maps, i generate xml file myself in browser, it work, but not showing in gmaps
Thank you in advance for all you helps .
I think your answer can be found here.
function parseXML(xml){
var bounds = new google.maps.LatLngBounds();
$(xml).find("marker").each(function(){
//Read the name, address, latitude and longitude for each Marker
var name = $(this).find('name').text();
var kap = $(this).find('kap').text();
var avai = $(this).find('avai').text();
var note = $(this).find('ket').text();
var type = $(this).find('type').text();
var lat = $(this).find('lat').text();
var lng = $(this).find('lng').text();
var markerCoords = new google.maps.LatLng(parseFloat(lat),
parseFloat(lng));
bounds.extend(markerCoords);
var marker = new google.maps.Marker({position: markerCoords, map:map});
});
map.fitBounds(bounds);
}

Google maps code markers codes works on firefox but not chrome or safari

I am creating a user map system that allows users to either select a new location or select a saved location (from an sql file). I want the map to load with a draggable marker that can be used to select a new position, with the lat/lng populating the relevant fields on the form. I also want the saved locations to populate a dropdown menu, allowing the users to select a location, the lat/lng and name will then populate the relevant fields and the draggable marker disappears from the map. When ‘Select a new location’ is selected from the dropdown menu, the ‘saved locations’ markers disappear and the draggable marker should reappear.
This is the code I have. I admit I am new to this, and have used the Google Maps Developer a lot, as well as searching online and have taken quite a while to get to this point.
This code does exactly what I want in Firefox and IE, but not in Chrome or Safari. In Chrome the saved locations appear in the dropdown menu but when I click on ‘select a new location’ after I have loaded a saved location, the draggable marker does not reappear. In Safari, the saved locations are not even loaded. I would appreciate any advice on how I can fix the errors with my code that could be causing this. I have tried debugging in Chrome (31.0.1650.57 ) and Safari (5.1.7 for windows), I get Cannot read property '_e3' of undefined of the main.js and also Unexpected token <
error404.000webhost.com/ (I’m hosting the site on 000webhost).
This is my html code:
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Sightings Form Member</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var markers = [];
var markerNew;
var infoWindow;
var infowindow;
var locationSelect;
var geocoder = new google.maps.Geocoder();
var imageNew = 'binoculars3.png';
var imageSave = 'star-3a.png';
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
console.log(responses);
updateMarkerAddress(responses[0].address_components[0].long_name);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerPosition(latLng) {
var MapLat =latLng.lat();
var MapLng =latLng.lng();
document.getElementById('latitude').value = MapLat;
document.getElementById('longitude').value = MapLng;
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
infowindow.open(map, markerNew);
infowindow.setContent(address);
}
function initialize() {
var latLng = new google.maps.LatLng(10.6667, -61.3152);
map = new google.maps.Map(document.getElementById("map"), {
center: latLng,
zoom: 8,
mapTypeId: 'hybrid',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.TOP_left
}
});
infoWindow = new google.maps.InfoWindow();
NewMarker(latLng);
infowindow = new google.maps.InfoWindow();
infowindow.setContent(address);
// Adds saved locations //Set up dropdown options
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none"){
google.maps.event.trigger(markers[markerNum], 'click');
}
};
//Read in saved locations
downloadUrl('RetrieveSavedLoc.php', function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("markerSave");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("loc_name");
var address = markerNodes[i].getAttribute("dayyear");
var savedlatlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
var MapLat = markerNodes[i].getAttribute("lat");
var MapLon = markerNodes[i].getAttribute("lng");
createOption(name, i);
createMarker(savedlatlng, name,MapLat,MapLon);
bounds.extend(savedlatlng);
}
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(markers[markerNum], 'click');
};
});
}
///Set up new marker
function NewMarker(latLng,address) {
markerNew = new google.maps.Marker({
position: latLng,
icon: imageNew,
map: map,
draggable: true,
crossOnDrag:false
});
google.maps.event.addListener(markerNew, 'drag', function() {
updateMarkerPosition(markerNew.getPosition());
document.getElementById('locname').value = '';
});
google.maps.event.addListener(markerNew, 'dragend', function() {
geocodePosition(markerNew.getPosition());
var newlatLng = markerNew.getPosition(); // returns LatLng object
map.setCenter(newlatLng);
});
}
//Saved location marker
function createMarker(savedlatlng, name,MapLat,MapLon) {
var html = "<b>" + name + "</b>";
var marker = new google.maps.Marker({
map: map,
icon: imageSave,
position: savedlatlng,
visible: false
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.close(); //Close MarkerNew infowindow
markerNew.setVisible(false);//Close MarkerNew
marker.setVisible(true);
setAllMap(map); //Allows saved markers to be put back on map
infoWindow.setContent(html);
infoWindow.open(map, marker);
document.getElementById('latitude').value = MapLat;
document.getElementById('longitude').value = MapLon;
document.getElementById('locname').value = name;
});
markers.push(marker);
}
//Reads saved locations into dropdown menu
function createOption(name, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name;
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() {}
// 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);
markerNew.setVisible(true);
}
// Sets the map on all markers in the array.
function setNewMap(map) {
for (var i = 0; i < markerNew.length; i++) {
markerNew[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkerNew() {
google.maps.event.addListener(map, "click", function () {
markerNew.setMap(null);
alert("Marker has been removed from map, about to restore it");
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<body id = "main_body">
</div>
<div id="mainouter">
<div class = "form description">
<form action="reviewMember.php" method="post">
<label style="font-size:1.4em;font-color:black;" class="description" for="location" >Where did you see it?* </label>
<label class="description" for="location"></label>
<div><select id="locationSelect" name="locationSelect" style="width:400px">
<option value="loc_new" onclick="clearMarkers();">Select a new location</option>
</select></div>
<div id="map" style="height: 300px;width: 400px;margin-right: 0.9em;float:left;"></div>
</form>
</div>
</body>
</html>
And php:
<?php
require("connectMap.php");
// 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
$con=mysqli_connect ($server, $user, $pass,$db);
if (!$con) { die('Not connected : ' . mysqli_error($con));}
session_start();
if(!isSet($_SESSION["email"],$_SESSION['uid'])) {
// Redirect user to login page
header("Location: login_final.php");
exit();
}else {
$userEmail = $_SESSION["email"];
}
// Select the member ID from the users table - to search for the id in the database
$sql = "SELECT * FROM users WHERE email ='$userEmail' LIMIT 1";
$user_query = mysqli_query($con, $sql);
// Now make sure that user exists in the table
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "That user does not exist or is not yet activated, press back";
exit();
}
// Fetch the user row from the query above
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$userID = $row["ID"];
}
// Select the member from the database table - this is to find the name of the user to input into the form and save into form database
$query = "SELECT * FROM locations WHERE userID ='$userID' ";
$result = mysqli_query($con,$query);
$dayyear = "";
if (!$result) {
die('Invalid query: ' . mysqli_error($con));
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysqli_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("markerSave");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("loc_name",$row['locname']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
}
echo $dom->saveXML();
?>

How do I delete field values of a table once window is closed?

I have 2 tables criminal and offender. i have created another table called subject where a query is executed and it works amazingly: HERE IS THE CODE:
showsubject.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<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">
var customIcons = {
criminal: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
offender: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(-20.1666591, 57.503457),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("showsubject-script1.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var subid = markers[i].getAttribute("subid");
var subaddress = markers[i].getAttribute("subaddress");
var subtype = markers[i].getAttribute("subtype");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("sublat")),
parseFloat(markers[i].getAttribute("sublng")));
var html = "<b>" + subid + "</b> <br/>" + subaddress;
var icon = customIcons[subtype] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
});
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() {}
</script>
</head>
<body onLoad="load()">
<div id="map" style="width: 900px; height: 1000px"></div>
</body>
</html>
SHOWSUBJECTSCRIPT.PHP
<?php
require("db.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;
}
$query1 = mysql_query ("SELECT id,address,lat,lng 'criminal' FROM criminal");
while ($row1 = mysql_fetch_array($query1) )
{
$insert1= mysql_query("insert into subject (subid,subaddress,sublet,sublng,subtype)
values( '$row[0]', '$row[1]', '$row[2]', '$row[3]','$row[4]') ");
}
$query2 = mysql_query ("SELECT id,address,lat,lng 'offender' FROM offender");
while ($row2 = mysql_fetch_array($query2) )
{
$insert2= mysql_query("insert into subject (subid,subaddress,sublat,sublng,subtype)
values( '$row[0]', '$row[1]', '$row[2]', '$row[3]','$row[4]') ");
}
$query3 = mysql_query ("SELECT * FROM subject");
header("Content-type: text/xml");
echo '<markers>';
while ($row3 = #mysql_fetch_assoc($query3)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'subid="' . parseToXML($row3['subid']) . '" ';
echo 'subaddress="' . parseToXML($row3['subaddress']) . '" ';
echo 'sublat="' . $row3['sublat'] . '" ';
echo 'sublng="' . $row3['sublng'] . '" ';
echo 'subtype="' . $row3['subtype'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
Now i have to delete the field values of the table offender once the session is closed. Anyone can help me please..??
The best way to do this is to use cron. Code the php script that will do the clean up and set up cron to run it every x minutes, hours to run it for you.
http://net.tutsplus.com/tutorials/php/managing-cron-jobs-with-php-2/
Another option could be using ignore_user_abort() depending on how exactly you want to remove the data from the offender table
http://php.net/manual/en/function.ignore-user-abort.php

Google Map not loading when running script (shows "map div")

I am trying to place markers where the cities in a mySQL database are. The page loads but it shows "map div" where the map should load. I am not sure what is wrong. Thank you for taking a look and trying to help!
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
directionsDisplay.setMap(map);
//create an array of latitudes, longitudes, and city names
var markers = [
<?php
//orgnize fans by city
$query = "SELECT city, state, COUNT(*) fans FROM users GROUP BY city ORDER BY fans DESC";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
//pulls the city, state code from the database and stores it as a string in $address
$address = urlencode('"' . $row['city'] . ", " . $row['state'] . '"');
$googleApi = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false';
$json = file_get_contents(sprintf($googleApi, $address));
$resultObject = json_decode($json);
$location = $resultObject->results[0]->geometry->location;
$lat = $location->lat;
$lng = $location->lng;
echo "{ lat: ".$lat.", lng: ".$lng.", name: ".'"'.$row['city'].", ".$row['state'].'"'."},";
}
?>
];
// Create the markers ad infowindows.
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
// Create the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.name
});
// Create the infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.name;
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "200px";
streetview.style.height = "200px";
content.appendChild(streetview);
var infowindow = new google.maps.InfoWindow({
content: content
});
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
google.maps.event.addListenerOnce(infowindow, "domready", function() {
var panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: false,
enableCloseButton: false,
addressControl: false,
linksControl: false,
visible: true,
position: marker.getPosition()
});
});
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Your Current City'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
When I open the html, I call initialize and make the canvas:
<body onload="initialize()">
<div id="map_canvas" style="width: 1100px; height: 450px;">map div</div>

Initializing google maps with multiple markers from an array

I'm passing 2 arrays into google maps, one for a location (which is geocoded) and another for that location's info window.
Is there any way I can initialize the map and plot all these points at once, or will I have to make a second function to plot more points? Since there are multiple points, I'm not sure how else to do it other than plotting one point, and then making an addition function which loops through the array and plots the rest.
Here's the code.
The two arrays(which I didn't include the code for) are $cityArray and $title
function initialize() {
geocoder = new google.maps.Geocoder();
latlang = geocoder.geocode( { 'address':
'<?php echo json_encode($cityArray); ?>'},
function(results, status) {
//use latlang to enter city instead of coordinates
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click',
(function(marker, i) {
return function() {
infowindow.setContent(
'<?php echo json_encode($title); ?>'
);
infowindow.open(map, marker);
}
})(marker, i));
markersArray.push(marker);
}
else{
alert("Geocode was not successful for the following reason: "
+ status);
}
});
var myOptions = {
center: latlang, zoom: 4, mapTypeId: google.maps.MapTypeId.SATELLITE,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
};
var gm = google.maps;
map = new google.maps.Map(document.getElementById("main_Content"),
myOptions);
plotMarkers();
} //end of initialization function
var infowindow = new google.maps.InfoWindow();
Please refer the following Sample which i have used for the above.,
Step1 : Include the Three script Files in header of your page.,like
(i). <scrip type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=Your_API_KEY"></script>
(ii).<scrip type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
(iii).<scrip type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>
Step2 : Scripts On Page
<script type="text/javascript">
//initialize the map window
jQuery(document).ready(function () {
load();
});
jQuery(window).unload(function () {
GUnload();
});
var map;
var geocoder;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function load() {
if (GBrowserIsCompatible()) {
geocoder = new GClientGeocoder();
map = new GMap2(document.getElementById('map'));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
//map.setCenter(new GLatLng(35.048629,-0.820663), 4);
searchLocations();
document.getElementById('directions-panel').innerHTML = '';
var url_new = ''+ benObj.TEMPLATE_DIR +'/print.html';
var print_icon_url_new = 'PrintLink';
jQuery('#print_icon').html(print_icon_url_new);
}
}
//Search Locations with address input
function searchLocations() {
var address = document.getElementById('addressInput').value;
// alert(address);
var address_new = jQuery("#addressInput_new").val();
if (address_new != "Enter City or Zip") {
jQuery("#loc1").html(address_new);
}
geocoder.getLatLng(address, function (latlng) {
//alert(latlng);
if (!latlng) {
alert(address + ' not found');
} else {
searchLocationsNear(latlng);
}
});
}
// Search Near By Location to place the Markers and Information windows
function searchLocationsNear(center) {
var radius = document.getElementById('radiusSelect').value;
var searchUrl = ''+ benObj.BASE_ROOT +'/mapmarker?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&format=raw';
jQuery.get(searchUrl, function (data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName('marker');
map.clearOverlays();
var sidebar = document.getElementById('sidebar');
var sidebar_val = '';
//sidebar.innerHTML = 'Results Found';
jQuery("#sidebar").html(sidebar_val);
<!--jQuery("#loc_count").html(markers.length);-->
if (markers.length == 0) {
sidebar.innerHTML = 'No results found.';
map.setCenter(new GLatLng(35.048629, -0.820663), 4);
return;
}
var bounds = new GLatLngBounds();
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute('name');
var address = markers[i].getAttribute('address');
var phone_new = markers[i].getAttribute('phonenumber');
var distance = parseFloat(markers[i].getAttribute('distance'));
var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
var markerchar = "b";
var marker = createMarker(point, name, address, phone_new);
map.addOverlay(marker);
// var location_count = jQuery('#loc_count').val();
jQuery('#loc_count').val(i + 1);
var sidebarEntry = createSidebarEntry(marker, name, address, distance, phone_new);
jQuery('#sidebar').append(sidebarEntry);
//sidebar.appendChild(sidebarEntry);
// ScrollPane.getContentPane().appendChild(sidebarEntry);
bounds.extend(point);
}
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
jQuery('#sidebar').jScrollPane();
//jQuery('#sidebar').reinitialise();
});
}
//To Create a Marker With Information Window
function createMarker(point, name, address, phone_new) {
var pinkIcon = new GIcon(G_DEFAULT_ICON);
pinkIcon.image = ""+ benObj.IMAGE_DIR +"addr-pin-1.png";
var markerOptions = {
icon: pinkIcon
};
var marker = new GMarker(point, markerOptions);
var event_calendar = "event_calendar";
var event_title = ""+ benObj.event_title +"";
var display = "block";
var e_dt_start = jQuery("#dtstart").val();
var e_dt_end = jQuery("#dtend").val();
var e_start_timestamp = (formatTimestring(e_dt_start));
var e_end_timestamp = (formatTimestring(e_dt_end));
var e_desc = jQuery("#edesc").val();
var StrippedString = e_desc.replace(/(<([^>]+)>)/ig, "");
var trimmed = StrippedString.replace(/^\s+|\s+$/g, '');
var html = '<b>' + name + '</b> <br/>' + address + '<br>contact: ' + phone_new + '<br><br>Add to Calendar<div class="summary" style="display:none;">' + event_title + ' - "' + name + '"</div><span class="dtstart date" title="' + e_dt_start + '" style="display:none;">8th Aug 2010</span><span class="dtend date" title="' + e_dt_end + '" style="display:none;">01:30am - 12:00pm</span><div class="event-desc" style="display:none;">' + trimmed + '</div><div class="event-locate" style="display:none;">' + name + ',' + address + '</div> | Remind Me<br><br>Get Direction From:<br><input type="hidden" id="start" value="' + address + '"><input type="text" id="end" value="" style="border: 1px solid #ECE6D5;"> <input type="button" value="GO" onclick="calcRoute();" style="border: 1px solid #ECE6D5;padding-left:5px;">';
GEvent.addListener(marker, 'click', function () {
marker.openInfoWindowHtml(html);
//jQuery(this).addtocal();
});
return marker;
}
// To Make Sidebar Entry If need
function createSidebarEntry(marker, name, address, distance, phone_new) {
var div = document.createElement('div');
var html = '<div class="locrow clearfix"><div class="left" style="width:240px;"><span class="count" id="loc_count">' + jQuery("#loc_count").val() + '</span><address><strong>' + name + '</strong>' + address + '</address><span class="mapdate"><span class="icon date"></span>'+ benObj.event_start_month_date +' – '+ benObj.event_end_month_date_year +'</span></div><div class="right" style="width:154px;"><ul><li><span class="icon phone"></span>' + phone_new + '</li><li><span class="icon time"></span>11 am – 7 pm</li><li><span class="icon car"></span>distance ' + distance.toFixed(1) + ' mi</li></ul></div></div>';
div.innerHTML = html;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
GEvent.addDomListener(div, 'click', function () {
GEvent.trigger(marker, 'click');
});
GEvent.addDomListener(div, 'mouseover', function () {
div.style.backgroundColor = '#eee';
});
GEvent.addDomListener(div, 'mouseout', function () {
div.style.backgroundColor = '#fff';
});
return div;
}
// To make a Directions If need
function calcRoute() {
directionsDisplay = new google.maps.DirectionsRenderer();
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var url = "http://maps.google.co.in/maps?f=d&source=s_d&saddr=" + start + "&daddr=" + end + "&aq=0&vpsrc=0&hl=en&doflg=ptm&mra=ls&ie=UTF8&t=m&z=5&layer=c&pw=2";
var print_icon_url = 'PrintLink';
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.850033, -87.6500523)
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
directionsDisplay.setDirections(response);
jQuery('#print_icon').html(print_icon_url);
}
});
}
</script>
//To Create a XML For Markers and Information Windows
<?php
function mapMarker($center_lat,$center_lng,$radius)
{
$mysqli = $this->_getMySqlConnection();
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Search the rows in the markers table
$query = sprintf("SELECT phone,street_address_1, store_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 locations HAVING distance < '%s' ORDER BY distance LIMIT 0 , 10",
$mysqli->real_escape_string($center_lat),
$mysqli->real_escape_string($center_lng),
$mysqli->real_escape_string($center_lat),
$mysqli->real_escape_string($radius));
$result = $mysqli->query($query);
header("Content-type: text/xml");
header('Access-Control-Allow-Origin: *');
$avoid_duplicate="";
// Iterate through the rows, adding XML nodes for each
while ($row = #$result->fetch_assoc())
{
if($avoid_duplicate!=$row['store_name'])
{
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", $row['store_name']);
$newnode->setAttribute("address", $row['street_address_1']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("distance", $row['distance']);
$newnode->setAttribute("phonenumber", $row['phone']);
$avoid_duplicate=$row['store_name'];
}
}
$outXML=$dom->saveXML();
$result->close();
$mysqli->close();
return $outXML;
}
?>
HTML Part :
<div class="mapleft">
<div class="ScrollPane scroll-pane" id="sidebar" style="overflow: auto; height: 430px;"></div>
<div class="mapshadow"></div>
</div>
<input type="hidden" id="addressInput" value="<?php echo $zip_code;?>" />
<input type="hidden" id="radiusSelect" value="50" />
<input type="hidden" id="addressInput_temp" value="<?php echo $zip_code;?>" />
<input type="hidden" id="radiusSelect_temp" value="50" />
<input type="hidden" name="X_REQUESTED_WITH" value="XMLHttpRequest" />
<div class="mapright">
<div id="map" style="width: 475px; height: 450px"></div>
</div>
<div class="map-dir" id="directions-panel" style="float:right;width:488px;"></div>
<input type="hidden" id="loc_count" value="1" />
These are the things which will produce the great out comes.

Categories