AJAX call to php database Google maps markers - javascript

I am trying to make connection with my database
$.ajax({
url: 'pictures.php', data: "", dataType: 'json', success: function (rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var name = row[1];
var pic = row[2];
var lat = row[3];
var lon = row[4];
$(addMarker( id + name + pic + lat + lon));
}
}
});
This is pictures.php:
<?php
$dbname = 'test'; //Name of the database
$dbuser = 'root'; //Username for the db
$dbpass = ''; //Password for the db
$dbserver = 'localhost'; //Name of the mysql server
$dbcnx = mysql_connect("$dbserver", "$dbuser", "$dbpass");
mysql_select_db("$dbname") or die(mysql_error());
$query = mysql_query("SELECT * FROM bezienswaardigheden");
$data = array();
while ( $row = mysql_fetch_row($query) )
{
$data[] = $row;
}
echo json_encode( $data );
exit
?>
This is the function addMarker:
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function () {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function () {
map.panTo(center);
currentPopup = null;
});
}
I cant see markers on google maps with this code. The maps works perfect, but I want markers for places I fill in the database :( AJAX don't make connect with pictures.php.

Related

How can I update a google maps marker with user submitted information?

Sorry if this is somewhat lengthy but I've had this problem for a while now. So basically I've followed both of these tutorials
https://developers.google.com/maps/documentation/javascript/mysql-to-maps
https://developers.google.com/maps/documentation/javascript/info-windows-to-db
These tutorials are for loading google map markers onto a canvas using google maps api and then also saving information about created markers from a user. I'm trying to essentially combine these 2 tutorials into something that allows me to load google map markers from a database (which I have done), and then allow a user to submit information about them from an infowindow which appears when a marker is clicked. The information that is submitted is to be updated in the marker's corresponding database row and then displayed when the marker is clicked. That part I'm having trouble on. I can't seem to get the marker's information in the database to update when the user hits the submit button in the infowindow. I'm trying to update the name of a quest that the user selects from a dropdown menu which appears in an infowindow upon clicking a marker.
I'll try to post only the code that's relevant to the problem. Any help would be appreciated, thank you
function initMap() {
var myCenter = new google.maps.LatLng(37.4419, -122.1419);
var mapCanvas = document.getElementById("map");
var mapOptions = {
center: myCenter,
zoom: 12
};
var map = new google.maps.Map(mapCanvas, mapOptions);
var infoWindow = new google.maps.InfoWindow;
infowindow = new google.maps.InfoWindow({
content: document.getElementById('form')
});
messagewindow = new google.maps.InfoWindow({
content: document.getElementById('message')
});
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click',
function() {
infoWindow.setContent(content);
infoWindow.open(map, marker);
});
}
//Loading in markers from DB via call.php
downloadUrl('call.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var name = markerElem.getAttribute('name'); //name of marker
document.getElementById("name").innerHTML = name;
var address = markerElem.getAttribute('address'); //address of marker
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var id = markerElem.getAttribute('id');
var content = document.getElementById('form');
var marker = new google.maps.Marker({
map: map,
position: point,
});
marker.addListener('click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
});
}); //end of downloadurl
} //end of initmap
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);
}
Here's the submit button's function
function saveData() {
if (document.getElementById("questType").value == "quest1") { //if quest1 is selected upon submission
alert("1");
var questTitle = "1";
}
var name = escape(document.getElementById('name').value);
var url = "phpsqlinfo_updaterow.php?name=" + name + "&questTitle=" + questTitle;
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
infowindow.close();
messagewindow.open(map, marker);
}
});
}
The previous 2 code blocks are most of my index.php
Here's my file where I attempt to update the database with the information submitted by the user. The only thing I'm trying to update is quest title.
<?php
require("phpsqlinfo_dbinfo.php");
include ("call.php");
$name = $_GET['name'];
$questTitle = $_GET['questTitle'];
$con=mysqli_connect ("localhost", $username, $password);
$db_selected = mysqli_select_db( $con, $database);
if (!$db_selected) {
die ('Can\'t use db : ' . mysqli_error());
}
$query = (("UPDATE markers SET questTitle ='$questTitle' WHERE name = '$name'"));
$result = mysqli_query($con,$query);
?>
Finally, here is my call.php which outputs the xml doc to the browser
<?php
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
include('connect.php');
$query = "SELECT * FROM markers WHERE 1";
$result = mysqli_query($con, $query);
if (!$result) {
die('Invalid query: ' . mysqli_error($con));
}
// Iterate through the rows, adding XML nodes for each
while ($row = mysqli_fetch_assoc($result)){
global $dom, $node, $parnode;
// 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['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("id",$row['id']);
$newnode>setAttribute("questTitle",$row['questTitle']);
}
header("Content-type: text/xml");
echo $dom->saveXML();
?>
It's been confusing for me on how to figure out how to tell which marker is being updated.
You could use the id property to figure out which marker is being updated.
1) Create a global variable called clickedMarker which will contain the reference to the marker who's infowindow is opened and is being submitted.
var clickedMarker;
2) While created the marker set the id property of the marker using the id retrieved from the database.
var id = markerElem.getAttribute('id');
var marker = new google.maps.Marker({
map: map,
position: point,
id: id
});
3) When a marker is clicked and infowindow is opened set the marker as the clickedMarker
marker.addListener('click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
clickedMarker = marker;
});
4) While saving the data you can retrieve the id from the clickedMarker and send it to your php file as an additional query param.
function saveData() {
if (document.getElementById("questType").value == "quest1") { //if quest1 is selected upon submission
alert("1");
var questTitle = "1";
}
var id = clickedMarker.id;
var name = escape(document.getElementById('name').value);
var url = "phpsqlinfo_updaterow.php?name=" + name + "&questTitle=" + questTitle + "&id=" + id;
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
infowindow.close();
messagewindow.open(map, marker);
}
});
}

my markers don't appear using google maps api v3, using php and javascript

i know this question appears a lot but i've done this three times and the markers still don't appear, for some reason when i call data.Latitude and data.Longitude when i move the cursor over Latitude or Longitude it appears undefined. I did this guiding myself with a tutorial i found on youtube which it works perfectly but it doesn't work to me. I'm new using php
Here's my php code getting my data from the database(im using MySQL).
<?php
class location
{
public $RouteID;
public $Latitude;
public $Longitude;
public $Battery;
public $DateObtained;
public $ID_DEVICE;
public $tableName = "geografia";
function setRouteID($RouteID) { $this->RouteID = $RouteID; }
function getRouteID() { return $this->RouteID; }
function setLatitude($Latitude) { $this->Latitude = $Latitude; }
function getLatitude() { return $this->Latitude; }
function setLongitude($Longitude) { $this->Longitude = $Longitude; }
function getLongitude() { return $this->Longitude; }
function setBattery($Battery) { $this->Battery = $Battery; }
function getBattery() { return $this->Battery; }
function setDate($DateObtained) { $this->DateObtained = $DateObtained; }
function getDate() { return $this->DateObtained; }
function setID_DEVICE($ID_DEVICE) { $this->ID_DEVICE = $ID_DEVICE; }
function getID_DEVICE() { return $this->ID_DEVICE; }
public function getLocations(){
require_once("db/DbConnect.php");
$sql = "SELECT RouteID,Latitude,Longitude,Battery,DateObtained FROM $this->tableName
WHERE RouteID IS NOT NULL";
while ($stmt = mysqli_query($connection, $sql)) {
return $stmt->fetch_all();
}
}
public function getAllLocations(){
$dbhost = 'localhost';
$dbName = 'intecespejo';
$dbuser = 'root';
$pass = '';
$connection = new mysqli($dbhost, $dbuser , $pass, $dbName);
require_once("db/DbConnect.php");
$sql = "SELECT Latitude,Longitude,Battery,DateObtained FROM $this->tableName";
while ($stmt = mysqli_query($connection, $sql)) {
return $stmt->fetch_all();
}
}
}
Here im calling the function from locations.php(the code above)
The first call is just to show one row data and the other is to show everything, later i will change that.
<?php
require 'locations.php';
$Geo = new location;
$coll = $Geo->getLocations();
$coll = json_encode($coll, true);
echo '<div id="data">' . $coll . '</div>';
$allData = $Geo->getAllLocations();
$allData = json_encode($allData, true);
echo '<div id="allData">' . $allData . '</div>';
?>
And here's my javascript code
var map;
function loadMap(){
var local = new google.maps.LatLng(18.487957, -69.961759) //{lat: 18.487957, lng: -69.961759}
map = new google.maps.Map(document.getElementById('map'), {
center: local,
zoom: 10
});
var marker = new google.maps.Marker({
position: local,
map: map
});
var cdata = JSON.parse(document.getElementById('data').innerHTML);
//console.log(cdata);
var DataLoc = JSON.parse(document.getElementById('allData').innerHTML);
showAllData(DataLoc);
}
function showAllData(DataLoc){
debugger;
Array.prototype.forEach.call(DataLoc, function(data){
//var localizacion = new google.maps.LatLng(data.Latitude, data.Longitude);
console.log(data);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.Latitude, data.Longitude),
map: map
});
})
}
Sorry if i'm asking the same question as other posts but i just can't figure out what's the problem and thanks in advance.

GoogleMaps v3 API Create only 1 marker on rightclick

I am working on a new project and I am new to the Google maps API.
I need your help to mark only one marker on the map. Our clients would indicate their location with a right click and only if they remove the existing marker they reinsert their location.
I have tried if and else and the only result is that the map does not load.
I have created a fiddle with the code hope it helps: http://jsfiddle.net/JG9bG/
$(document).ready(function () {
var mapCenter = new google.maps.LatLng(39.39987199999999, -8.224454000000037); //Google map Coordinates
var map;
map_initialize(); // initialize google map
//############### Google Map Initialize ##############
function map_initialize() {
var googleMapOptions = {
center: mapCenter, // map center
zoom: 7, //zoom level, 0 = earth view to higher value
maxZoom: 18,
minZoom: 7,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL //zoom control size
},
scaleControl: true, // enable scale control
mapTypeId: google.maps.MapTypeId.ROADMAP // google map type
};
map = new google.maps.Map(document.getElementById("google_map"), googleMapOptions);
//Load Markers from the XML File, Check (map_process.php)
$.get("map_process.php", function (data) {
$(data).find("marker").each(function () {
var name = $(this).attr('name');
var address = '<p>' + $(this).attr('address') + '</p>';
var type = $(this).attr('type');
var point = new google.maps.LatLng(parseFloat($(this).attr('lat')), parseFloat($(this).attr('lng')));
create_marker(point, name, address, false, false, false, "http://google.com/mapfiles/ms/micons/blue.png");
});
});
//Right Click to Drop a New Marker
myListener = google.maps.event.addListener(map, 'rightclick', function (event) {
//Edit form to be displayed with new marker
var EditForm = '<p><div class="marker-edit">' +
'<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker">' +
'<label for="pid"><span> Property Id: </span><input type="text" readonly name="pid" class="save-propid" value="<?php echo $prop_id;?>" maxlength="40" /></label>' +
'<label for="pName"><span>Place Name :</span><input type="text" name="pName" class="save-name" placeholder="Enter Title" maxlength="40" /></label>' +
'<label for="pDesc"><span>Description :</span><textarea name="pDesc" class="save-desc" placeholder="Enter Address" maxlength="150"></textarea></label>' +
//'<label for="pType"><span>Type :</span> <select name="pType" class="save-type"><option value="Rent">Rent</option><option value="Sell">Sell</option><option value="Holiday Rentals">Holiday Rentals</option></select></label>'+
'</form>' +
'</div></p><button name="save-marker" class="save-marker">Save Marker Details</button>';
//Drop a new Marker with our Edit Form
create_marker(event.latLng, 'Insert your Property Location', EditForm, true, true, true, "http://google.com/mapfiles/ms/micons/green.png");
});
}
//############### Create Marker Function ##############
function create_marker(MapPos, MapTitle, MapDesc, InfoOpenDefault, DragAble, Removable, iconPath) {
//new marker
var marker = new google.maps.Marker({
position: MapPos,
map: map,
draggable: DragAble,
animation: google.maps.Animation.DROP,
title: "Hello World!",
icon: iconPath
});
//Content structure of info Window for the Markers
var contentString = $('<div class="marker-info-win">' +
'<div class="marker-inner-win"><span class="info-content">' +
'<h1 class="marker-heading">' + MapTitle + '</h1>' + MapDesc +
'</span><button name="remove-marker" class="remove-marker" title="Remove Marker">Remove Marker</button>' +
'</div></div>');
//Create an infoWindow
var infowindow = new google.maps.InfoWindow();
//set the content of infoWindow
infowindow.setContent(contentString[0]);
//Find remove button in infoWindow
var removeBtn = contentString.find('button.remove-marker')[0];
var saveBtn = contentString.find('button.save-marker')[0];
//add click listner to remove marker button
google.maps.event.addDomListener(removeBtn, "click", function (event) {
remove_marker(marker);
});
if (typeof saveBtn !== 'undefined') //continue only when save button is present
{
//add click listner to save marker button
google.maps.event.addDomListener(saveBtn, "click", function (event) {
var mReplace = contentString.find('span.info-content'); //html to be replaced after success
var mName = contentString.find('input.save-name')[0].value; //name input field value
var mDesc = contentString.find('textarea.save-desc')[0].value; //description input field value
//var mType = contentString.find('select.save-type')[0].value; //type of marker
var mpid = contentString.find('input.save-propid')[0].value; //prop id
if (mName == '' || mDesc == '') {
alert("Please enter Name and Description!");
} else {
save_marker(marker, mName, mDesc, /*mType, */ mpid, mReplace); //call save marker function
}
});
}
//add click listner to save marker button
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker); // click on marker opens info window
});
if (InfoOpenDefault) //whether info window should be open by default
{
infowindow.open(map, marker);
}
}
//############### Remove Marker Function ##############
function remove_marker(Marker) {
/* determine whether marker is draggable
new markers are draggable and saved markers are fixed */
if (Marker.getDraggable()) {
Marker.setMap(null); //just remove new marker
} else {
//Remove saved marker from DB and map using jQuery Ajax
var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
var myData = {
del: 'true',
latlang: mLatLang
}; //post variables
$.ajax({
type: "POST",
url: "http://.../.../.../cpanel.php?exe=client_properties/google/map_process",
data: myData,
success: function (data) {
Marker.setMap(null);
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError); //throw any errors
}
});
}
}
//############### Save Marker Function ##############
function save_marker(Marker, mName, mAddress, /*mType, */ mpid, replaceWin) {
//Save new marker using jQuery Ajax
var mLatLang = Marker.getPosition().toUrlValue(); //get marker position
var myData = {
name: mName,
address: mAddress,
latlang: mLatLang,
/*type : mType, */
propid: mpid
}; //post variables
console.log(replaceWin);
$.ajax({
type: "POST",
url: "http://.../.../.../cpanel.php?exe=client_properties/google/map_process",
data: myData,
success: function (data) {
replaceWin.html(data); //replace info window with new html
Marker.setDraggable(false); //set marker to fixed
Marker.setIcon('http://google.com/mapfiles/ms/micons/blue.png'); //replace icon
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError); //throw any errors
}
});
}
});
Thanks for your help
Backend:
<?php
//PHP 5 +
// database settings
$db_username = '';
$db_password = '';
$db_name = '';
$db_host = 'localhost';
//mysqli
$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);
if (mysqli_connect_errno())
{
header('HTTP/1.1 500 Error: Could not connect to db!');
exit();
}
################ Save & delete markers #################
if($_POST) //run only if there's a post data
{
//make sure request is comming from Ajax
$xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
if (!$xhr){
header('HTTP/1.1 500 Error: Request must come from Ajax!');
exit();
}
// get marker position and split it for database
$mLatLang = explode(',',$_POST["latlang"]);
$mLat = filter_var($mLatLang[0], FILTER_VALIDATE_FLOAT);
$mLng = filter_var($mLatLang[1], FILTER_VALIDATE_FLOAT);
//Delete Marker
if(isset($_POST["del"]) && $_POST["del"]==true)
{
$results = $mysqli->query("DELETE FROM tblmarkers WHERE geo_lat=$mLat AND geo_lng=$mLng");
if (!$results) {
header('HTTP/1.1 500 Error: Could not delete Marker!');
exit();
}
exit("Done!");
}
$mName = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$mAddress = filter_var($_POST["address"], FILTER_SANITIZE_STRING);
/* $mType = filter_var($_POST["type"], FILTER_SANITIZE_STRING);*/
$mpid = filter_var($_POST["propid"], FILTER_SANITIZE_STRING);
$results = $mysqli->query("INSERT INTO tblmarkers (geo_name, geo_address, geo_lat, geo_lng, prop_id) VALUES ('$mName','$mAddress',$mLat, $mLng, '$mpid')");
/* $results = $mysqli->query("INSERT INTO tblmarkers (geo_name, geo_address, geo_lat, geo_lng, geo_type, prop_id) VALUES ('$mName','$mAddress',$mLat, $mLng, '$mType', '$mpid')");*/
if (!$results) {
header('HTTP/1.1 500 Error: Could not create marker!');
exit();
}
$output = '<h1 class="marker-heading">'.$mName.'</h1><p>'.$mAddress.'</p>';
exit($output);
}
################ Continue generating Map XML #################
//Create a new DOMDocument object
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers"); //Create new element node
$parnode = $dom->appendChild($node); //make the node show up
// Select all the rows in the markers table
$results = $mysqli->query("SELECT * FROM tblmarkers WHERE 1");
if (!$results) {
header('HTTP/1.1 500 Error: Could not get markers!');
exit();
}
//set document header to text/xml
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while($obj = $results->fetch_object())
{
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("geo_name",$obj->name);
$newnode->setAttribute("geo_address", $obj->address);
$newnode->setAttribute("geo_lat", $obj->lat);
$newnode->setAttribute("geo_lng", $obj->lng);
$newnode->setAttribute("geo_type", $obj->type);
}
echo $dom->saveXML();
Try this :
google.maps.event.addListener(map, "rightclick",function(event){
marker = new google.maps.Marker({
position: event.latLng,
title: 'Changer la position',
map: map,
draggable: true
});
this is an example : http://jsfiddle.net/hweb/M7K4L/
One option:
declare the marker globally (outside of any function definition):
var marker = null;
check to see if it exists, if it does delete it before creating one at the new location:
function create_marker(MapPos, MapTitle, MapDesc, InfoOpenDefault, DragAble, Removable, iconPath) {
if ((marker != null) && marker.setMap) {
marker.setMap(null);
marker = null;
}
//new marker
marker = new google.maps.Marker({
position: MapPos,
map: map,
draggable: DragAble,
animation: google.maps.Animation.DROP,
title: "Hello World!",
icon: iconPath
});
working fiddle

How to refresh only a div, not the complete page

I have this code that selects the type of a restaurant. After selecting any type the page is refreshed and after some SQL processing I get all restaurants corresponding to the selected type and show it in Google Maps.
How can I do that without refreshing the complete page, like only refreshing the <div> containing Google Maps?
<select class="mapleftS" name="type" id="type" onchange="changeType(this.value)">
<option value="0">كل الانواع</option>
<?$type = mysql_query("select * from rest_type ");
while($rod = mysql_fetch_array( $type )) {
if($rod[id] == $_REQUEST['type'])
$selll = 'selected';
else {$selll = '';
?>
<option value="<?=$rod[id]?>" <?=$selll?> ><?=$rod[name]?></option>
<? } ?>
</select>
<script>
function changeType( id ) {
parent.location = '?type=' + id;
}
$(function() {
var text_menu = $("#type option:selected").text();
$("#ddddd_").html(text_menu);
});
</script>
After selection this code is run:
if($_REQUEST['type']) {
// do some thing and refrsh map div
} else {
// do some thing and refrsh map div
}
And the following element contains Google Maps:
<div id="mppp" class="map"></div>
JS for Google Maps:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=SOMEAPIKEY&sensor=true"></script>
<script type="text/javascript">
var address_index = 0, map, infowindow, geocoder, bounds, mapinfo, intTimer;
$(function (){
mm();
});
mm = function() {
// Creating an object literal containing the properties you want to pass to the map
var options = {
zoom: 15,
center: new google.maps.LatLng(24.701564296830245, 46.76211117183027),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Creating the map
map = new google.maps.Map(document.getElementById('mppp'), options);
infowindow = new google.maps.InfoWindow();
geocoder = new google.maps.Geocoder();
bounds = new google.maps.LatLngBounds();
//******* ARRAY BROUGHT OVER FROM SEARCHRESULTS.PHP **********
mapinfo = [ <?=$da?> ];
intTimer = setInterval("call_geocode();", 300);
}
function call_geocode() {
if( address_index >= mapinfo.length ) {
clearInterval(intTimer);
return;
}
geocoder.geocode({
location: new google.maps.LatLng(mapinfo[address_index][6], mapinfo[address_index][7])
}, (function(index) {
return function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// Scale our bounds
bounds.extend(results[0].geometry.location);
var $id = mapinfo[index][0];
var $tell = mapinfo[index][3];
var $title = mapinfo[index][2];
var $img_src = mapinfo[index][3];
var img_src = mapinfo[index][1];
var $logo = mapinfo[index][4];
var $status = mapinfo[index][5];
var $sell = mapinfo[index][6];
var $city = mapinfo[index][8];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(mapinfo[index][6], mapinfo[index][7]),
icon: {
url : '<? bloginfo('url'); ?>' + img_src + '',
scaledSize : new google.maps.Size(50,50)
},
map: map,
scrollwheel: false,
streetViewControl: true,
title: $title
});
google.maps.event.addListener(marker, 'click', function() {
// Setting the content of the InfoWindow
if (img_src) {
var imdd = '<img src="<? bloginfo('url'); ?>' + img_src + '" width="60" height="60" style="margin-left:4px;float:right;" />';
}
else {
var imdd = '';
}
if ($tell) {
var tell = 'رقم الهاتف : '+$tell+'<br>';
}
else {
var tell = '';
}
if ($status) {
var status = 'الحي : '+$status+'<br>';
}
else {
var status = '';
}
if ($city) {
var city = 'المدينة : '+$city+'<br>';
}
else {
var city = '';
}
var content = '<div id="info" style="direction:rtl;font:15px time new roman;font-weight:bolder;position:relative;width:210px;"><div style=" font-size:13px;font-family:Tahoma;font-weight:bolder;text-align:center;font-weight:bold">' + $title + '</div><br><div style="float:right">' + imdd + '</div><div style="float:right;text-align:right;font-family:Tahoma">' + tell + city + status + '</div><br /><a style="float:left;color:#d22f00;font-size:12px;font-family:Tahoma" href="<? bloginfo('url'); ?>/rest-det/?id=' + $id + '">المزيد+</a></div>';
infowindow.setContent(content);
infowindow.open(map, marker);
});
map.fitBounds(bounds);
if (mapinfo.length == 1) {
map.setZoom(12);
}
}
else {
// error!! alert (status);
}
}
}
)(address_index)
);
address_index++;
}
</script>
<div id="mppp" class="map"></div>
You can use an AJAX pattern to refresh part of your page.
move your SQL code into another script - e.g. query.php
return a list of results in a JSON format
when the list changes call runQuery
use the function to parse the returned data and update your map
<script>
function runQuery() {
$.ajax({
url: "query.php?type="+ $("#type").val(),
cache: false,
success: function(data){
// code to process your results list;
}
});
}
</script>
This is an AJAX concept where you are able to change only a portion of your page without having to do a full page refresh or Postback.
You will find a ton of examples on what you are trying to do but the main concept is that you will:
-Take user input
-call back to your server with values
-have the server return you information that you then use to append or overwrite a portion of the page

Google map api search markers from database in specifc area

I've set up google map API that loads data from mysql database and display markers. the problem I am facing is that all the markers shows up at once no matter whatever I input in search location field.............. I want to show only the searched area and markers in that area. It shouldn't display all the markers at once but only the marker in the searched area.
I mean I want to zoom the map to the searched area. Currently if I've only one marker map zoom in to show that but if I've many markers the map zoom out to show all the markers. Here is the map I'm working on "http://funfeat.com/clients/gmap/gmap3.html" NOW I've set markers very very far and the map is still showing all the markers by zooming out.
The gmap.php is the file that provide xml results from mysql database. and the below code is what I am using to display map
<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.googleapis.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: 10,
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 = 'gmap.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="25" selected>25mi</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>
http://funfeat.com/clients/gmap/gmap.php?lat=47&lng=-122&radius=2 produces valid XML but your query must be wrong .It pulls out 10 markers, 9 of which are correct but the 10th produces <marker name="Pakistan" address="Chowk Azam, Layyah" lat="31.008364" lng="71.224342" type="cITY"/> which is certainly not within 2 miles of the coordinates. Your query should not pick up the last marker from the database.
As the use of mysql_ functions are discouraged the following code uses PDO can be used
//dependant on your setup
$host= "WWW";
$username="XXX";
$password="YYY";
$database="ZZZ";
// 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);
//Connect to database
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
// Prepare statement
$stmt = $dbh->prepare("SELECT name, lat, lng, ( 3959 * acos( cos( radians(?) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(?) ) + sin( radians(?) ) * sin( radians( lat ) ) ) ) AS distance FROM gbstn HAVING distance < ? ORDER BY distance ASC LIMIT 0 , 20");
// Assign parameters
$stmt->bindParam(1,$center_lat);
$stmt->bindParam(2,$center_lng);
$stmt->bindParam(3,$center_lat);
$stmt->bindParam(4,$radius);
//Execute query
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
EDIT Added to catch error if no records found
if ($stmt->rowCount()==0) {
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", "No Records Found");
$newnode->setAttribute("lat", $center_lat);//Sends marker to search location
$newnode->setAttribute("lng", $center_lng);
$newnode->setAttribute("distance", 0);
}
else {
End of EDIT
// Iterate through the rows, adding XML nodes for each
while($row = $stmt->fetch()) {
$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();
}
catch(PDOException $e) {
echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing
file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", gmap.php, ". $e->getMessage()."\r\n", FILE_APPEND);
}
//Close the connection
$dbh = null;
The part of the query above HAVING distance < '%s' is the part that should weed out the last marker.
I have added Error catch if no records are found in search and Map sent to lat/lng 0,0. See My Implementation Here

Categories