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
Related
I have a google map with all the parking in town. It works fine.
Now, for each parking i want to ask to a JSON file if the parking is full or not.
So, during the construction of the infoWindow popup i have a json with ajax/php and if it's a success i fill the paragraphe with "open" or "close" and if it's an error with "close".
During the "success" step of the ajax, if i console.log the result, i can see "open" or "close", but in the infoWindow its always show "undefined".
I read a lot of topics, nothing helps. I think there is a DOM problem ?
Here's my javascript, again I specify, everything works, the PHP file is called, the JSON is parsed, the number of places is read and the status "open" or "closed" is returned.
However the variable "msg" returns "open" or "close" in console.log but in "return in the paragraph" it only returns "undefined"...
JS :
<script>
function placesParking(idCUS) {
var URLPHP = 'https://www.example.com/';
var urlDynamique = URLPHP + 'parkingsStatus.php';
$.ajax({
url: urlDynamique,
icon: "GET",
crossDomain: true,
cache: false,
datatype: 'json',
data: 'idCUS=' + idCUS,
success: function(msg) {
return msg;
},
error: function(msg) {
return 'Aucune information';
}
});
}
function initMap() {
var currentPopup = null;
const mapOptions = {
center: {
lat: parseFloat(<?php echo $latitude; ?>),
lng: parseFloat(<?php echo $longitude; ?>)
},
zoom: 14,
streetViewControl: false,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapStades"), mapOptions);
let contentString;
let infowindow;
$.getJSON("./Fichiers/JSON/France/parkings.json", function (jsonMarkers) {
$.each(jsonMarkers, function (key, data) {
let latLng = new google.maps.LatLng(data.lat, data.lng);
const imageMap = 'Design/markerParking.png';
let marker = new google.maps.Marker({
position: latLng,
map: map,
icon: imageMap
});
contentString = '<div class="gmapWrap">'
+ '<p>' + data.nom + '</p>'
+ '<p>' + data.adresse + '</p>'
+ '<p>' + placesParking(data.idCUS) + '</p>'
+ '</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
marker.addListener("click", () => {
if(currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
infowindow.open({
anchor: marker,
map,
shouldFocus: false
});
currentPopup = infowindow;
});
marker.addListener(infowindow, "closeclick", function() {
currentPopup = null;
});
});
});
}
initMap();
</script>
And the php file
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET");
header('Content-Type: application/json');
include("./Admin/MISC/system.php");
if(isset($_GET["idCUS"])) {
$idCUS = sf($_GET["idCUS"]);
$url = "https://data.strasbourg.eu/explore/dataset/occupation-parkings-temps-reel/download/?format=json&timezone=Europe/Berlin&lang=fr";
$json = file_get_contents($url);
$json = json_decode($json);
foreach($json as $line) {
$champs = $line->fields;
$idCUSParking = $champs->idsurfs;
$nomParking = $champs->nom_parking;
$etatParking = $champs->etat_descriptif;
$placesLibres = $champs->libre;
if($idCUSParking == $idCUS) {
if($etatParking == 'frequentation temps reel indisponible') {
echo json_encode('Aucune information');
} else {
echo json_encode($etatParking);
}
}
}
} else {
echo json_encode('Aucune 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);
}
});
}
I try to show on a google map markers that are near the current positon. If the map is dragged it will update the center coordinates and recalculate the markers around that center. The initial markers around the current users positon are showing correctly but when i drag the map they stay all the time the same. The update and the POST both is happening (my guess that the POST is not finished before the markers reload, so the old ones stay). The sourrounding markers are stored in a session variable.
Controller showNearbyUsers method:
/**
* Shows the users near the current one
*
* #return void
*/
public static function showNearbyUsers($centerlat,$centerlng)
{
try {
// Delete the session variable
if (Session::has('nearbies'))
{
Session::forget('nearbies');
}
// Define max, min for lat and lng
$centerlatlow = $centerlat-0.25;
$centerlathigh = $centerlat+0.25;
$centerlnglow = $centerlng-0.25;
$centerlnghigh = $centerlng+0.25;
$nearbies = DB::table('positions')->join('users', 'users.id', '=', 'positions.users_id')
->where('users_id', '!=', Auth::id())
->whereBetween('lat', array($centerlatlow, $centerlathigh))
->whereBetween('lng', array($centerlnglow, $centerlnghigh))
->select('positions.*', 'users.name', 'users.level')
->get();
if ($nearbies) {
return Session::put('nearbies', $nearbies);
}
} catch(\Exception $e) {
Session::flash('message', 'An error occured with your localization. Enable GPS and refresh.');
Session::flash('alert-class', 'alert-danger');
}
}
View Script
<script>
// Auto adjust map div
$(window).resize(function () {
var h = $(window).height(),
offsetTop = 220; // Calculate the top offset
$('#map_canvas').css('height', (h - offsetTop));
}).resize();
// Setup token security
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
// Attributes
var map;
var geocoder;
var markers = Array(); // Contains x,y
var users = Array(); // Contains whole user info
var current = Array();
var infoWindows = Array();
var mapCenter;
// Test initialize users array
//users = [['Brugg',47.47963,8.18465],['Aarau',47.39340,8.04312],['Baden',47.47377,8.30647]];
// Initialize the map with logged in user
function initialize() {
geocoder = new google.maps.Geocoder();
getLocation();
}
// Set nearby user markers
function setMarkers(list) {
for(var i=0; i<list[0].length; i++){
var element = (list[0])[i];
var nearbyLatLng = new google.maps.LatLng(element['lat'], element['lng']);
console.log((list[0])[i]);
markers[i] = new google.maps.Marker({
position: nearbyLatLng,
map: map,
title: element['name'],
infoWindowIndex : i
});
infoWindows[i] = new google.maps.InfoWindow({
content : element['name']
});
google.maps.event.addListener(markers[i], 'click',
function(event)
{
infoWindows[this.infoWindowIndex].open(map, this);
}
);
}
}
// Delete nearby user markers
function deleteMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
// Map dragging listener. Updates the nearby users markers
function mapDragListener() {
google.maps.event.addListener(map, 'dragend', function() {
deleteMarkers();
mapCenter = map.getCenter();
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
async: false
});
#if(Session::has('nearbies'))
<?php $test = Session::get('nearbies'); ?>
users = [<?php echo json_encode($test); ?>];
console.log(users);
#endif
setMarkers(users);
});
}
// Map zoom listener. Updates the nearby users markers
function mapZoomListener() {
}
// Get current user location
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
} else {
alert("Geolocation is not supported by this browser.");
}
}
// If success in finding current position
function geoSuccess(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// Send to geocoordinates.php and save to DB
$.post("updateme/"+lat+"/"+lng);
mainMapCalc(lat, lng);
}
// If no success in finding current position
function geoError() {
alert("Please enable Geo-Location and Refresh the Website.");
}
// Set the logged in users and build up the environment
function mainMapCalc(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if(results[1]) {
//formatted address
var address = results[0].formatted_address;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 18,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
mapCenter = map.getCenter();
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
async: false
});
<?php $test = Session::get('nearbies'); ?>
users = [<?php echo json_encode($test); ?>];
setMarkers(users); // Set initial nearby markers
mapDragListener(); // Register Listener
//mapZoomListener(); // TODO: Register Listener
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
} else {
alert("Geocoder Error// No results found");
}
} else {
alert("Geocoder Error// Failed due to: " + status);
}
});
}
// Show Map
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Where is here the problem?
Thanks in advance
It looks like the problem is that you are sending out the ajax request, but you are not doing anything with the returned data. Try changing
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
async: false
});
to
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
success: function(data, textStatus, jqXHR) {
// request succeeded
// data - response from server
},
error: function (jqXHR, textStatus, errorThrown){
// the request failed
}
});
Also note that async: false is deprecated: https://api.jquery.com/jQuery.ajax/#options, so you should use callbacks as shown above.
I already have a working map where it generates a valid xml and can generate a marker on my map. Now what I want to do is to upon generating of maps for each loop in the xml I can create asynchronously a check box for each name. here is the code that generates the xml
function searchNearLocations(radius){
clearLocations();
var searchUrl = './designIncludes/phpLogicIncludes/searchMarkers.php?lat=' + userLat +'&lng=' + userLng + '&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 info = markerNodes[i].getAttribute("info");
var tts = markerNodes[i].getAttribute("tts");
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createMarker(latlng, name, address,info,tts);
createCheckboxes(name);
bounds.extend(latlng);
}
map.fitBounds(bounds);
});
}
My createMarker()
function createMarker(latlng, name, address,info,tts) {
var html = "<b>" + name + "</b></br><u>" + address + "</u></br>" + info + "</br>" + "Time allowance to spend: " + tts;
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);
}
I'm not that good in javascript but I have a marker=[] array global variable. Can I use that variable to generate a checkbox with it?by the way I also have a pre made marker before invoking the searchNearLocations function and I want to add it on the latlng bounds. Is it possible to insert it on the loop?
Okay
Everything not having to do with the checkboxes, I ignored. You'll have to put it back in your code.
I wrote a functioning example, you can copy/paste this as is.
<script src="http://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script type="text/javascript">
var markers = [];
var map;
/* I don't have that XML. I'll just insert a few locations hard coded. You can ignore this; it doesn't affect your question */
var markerNodes = [
{latlng: new google.maps.LatLng(50.896328544032805,4.4825010816688), name: 'Brussels Airport', address: 'A201, 1930 Zaventem', info: 'National airport of Brussels', tts: 'foo'},
{latlng: new google.maps.LatLng(50.8957080950929,4.334064952575659), name: 'Football stadion', address: 'Marathonlaan', info: 'Football stadion of the Red Devils', tts: 'foo'},
{latlng: new google.maps.LatLng(50.82302545625156,4.39255052014533), name: 'VUB campus', address: 'Pleinlaan 2', info: 'University of Brussels', tts: 'foo'}
];
function initialize() {
var position = new google.maps.LatLng(50.84499325563654,4.349978498661017);
var myOptions = {
zoom: 11,
center: position
};
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
searchNearLocations(null); // I ignore the radius part. I presume this searches for locations in a DB, or something...
}
/* never mind most of the changes I made here, it's just to ignore the xml part of the code */
function searchNearLocations(radius) {
clearLocations();
var bounds = new google.maps.LatLngBounds();
for (var i=0; i<markerNodes.length; i++) {
var latlng = markerNodes[i].latlng,
name = markerNodes[i].name,
address = markerNodes[i].address,
info = markerNodes[i].info,
tts = markerNodes[i].tts;
createMarker(latlng, name, address, info, tts);
createCheckbox(name, i); // the most important thing is to pass the i; then markers[i] corresponds with checkboxes[i]
bounds.extend(latlng);
}
map.fitBounds(bounds);
}
function createMarker(latlng, name, address, info, tts) {
// var html = "<b>" + name + "</b></br><u>" + address + "</u></br>" + info + "</br>" + "Time allowance to spend: " + tts;
var marker = new google.maps.Marker({
map: map,
title: name, // You should add this
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
/* I'll ignore the infoWindow */
});
markers.push(marker);
}
function clearLocations() {
for (var i=0; i<markers.length; i++) {
markers[i].setMap(null);
}
markers=[];
}
function checkboxChanged(i, checked) {
if(checked) {
markers[i].setMap(map);
}
else {
markers[i].setMap(null);
}
}
function createCheckbox(name, i) {
document.getElementById('checkboxes').innerHTML +=
'<input type="checkbox" checked="checked" onclick="checkboxChanged(' + i + ', this.checked);"> ' + name + '<br>';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#map-canvas {
width: 500px;
height: 400px;
}
</style>
<div id="map-canvas"></div>
<div id="checkboxes"></div>
Can you manage to include this in your code?
EDIT:
Here is an example of locations in a DB; I bypass xml and communicate through JSON.
It gives you (kind of) a combination of your questions;
I have a different table on my DB, but that shouldn't be a problem.
I add jQuery, just for ajax.
CREATE TABLE IF NOT EXISTS stations (
id bigint(15) NOT NULL AUTO_INCREMENT,
lat decimal(12,10) DEFAULT NULL,
lng decimal(12,10) DEFAULT NULL,
name varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
INSERT INTO stations (id, lat, lng, name) VALUES
(1, '50.8456035000', '4.3568658000', 'Brussel-Centraal'),
(2, '50.8413140000', '4.3490830000', 'Brussel-Kapellekerk'),
(3, '50.8517507000', '4.3623635000', 'Brussel-Congres'),
(4, '50.8604931000', '4.3607035000', 'Brussel-Noord'),
(5, '50.8348278000', '4.3365303000', 'Brussel-Zuid');
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script type="text/javascript">
var markers = [];
var map;
// settings, to pass to the DB
var lat = 50.84499325563654;
var lng = 4.349978498661017;
var radius = 1.5; /* set this to more than 1.5 to see more locations */
function initialize() {
var position = new google.maps.LatLng(50.84499325563654, 4.349978498661017);
var myOptions = {
zoom: 11,
center: position
};
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
searchNearLocations(lat, lng, radius);
}
function searchNearLocations(lat, lng, radius) {
document.getElementById('checkboxes').innerHTML = '';
// we start an Ajax call.
$.ajax({
url: 'ajax.php',
data: {lat: lat, lng: lng, radius: radius},
dataType: 'json',
success: function(data) {
// the request has returned data. Now we can proceed
clearLocations();
var bounds = new google.maps.LatLngBounds();
for (var i=0; i<data.length; i++) {
var latlng = new google.maps.LatLng(data[i].lat, data[i].lng),
name = data[i].name;
/* add what ever extra data you need */
createMarker(latlng, name, null, null, null);
createCheckbox(name, i); // the most important thing is to pass the i; then markers[i] corresponds with checkboxes[i]
bounds.extend(latlng);
}
map.fitBounds(bounds);
}
});
}
function createMarker(latlng, name, address, info, tts) {
/* var html = "<b>" + name + "</b></br><u>" + address + "</u></br>" + info + "</br>" + "Time allowance to spend: " + tts; */
var marker = new google.maps.Marker({
map: map,
title: name, // You should add this
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
/* I'll ignore the infoWindow */
});
markers.push(marker);
}
function clearLocations() {
for (var i=0; i<markers.length; i++) {
markers[i].setMap(null);
}
markers=[];
}
function checkboxChanged(i, checked) {
if(checked) {
markers[i].setMap(map);
}
else {
markers[i].setMap(null);
}
}
function createCheckbox(name, i) {
document.getElementById('checkboxes').innerHTML +=
'<input type="checkbox" checked="checked" onclick="checkboxChanged(' + i + ', this.checked);"> ' + name + '<br>';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#map-canvas {
width: 500px;
height: 400px;
}
</style>
<div id="map-canvas"></div>
<div id="checkboxes"></div>
ajax.php
<?php
$link = mysqli_connect('localhost', 'root', '', 'stackoverflow'); /* put your settings back */
if(!$link) {
die ('unable to connect to the database' . mysqli_connect_error());
}
//Get parameters from URL
$myLat = (isset ($_GET['lat']) ? $_GET['lat'] : 0.0); // give it some default
$myLng = (isset ($_GET['lng']) ? $_GET['lng'] : 0.0);
$calcDistance = (isset ($_GET['radius']) ? $_GET['radius'] : 1.0);
//Search the rows in the markers table
/* I have a slightly different table; I'll continue with mine; it's easy to put everything back */
// $query = sprintf("SELECT siteName,address,lat,lng,info,tts, (6371 * acos(cos(radians('%s')) * cos(radians(lat)) * cos(radians(lng) - radians ('%s')) + sin(radians('%s')) * sin(radians(lat))))AS distance FROM mapTable HAVING distance < '%s' ORDER BY distance LIMIT 0, 50",
$query = sprintf("SELECT id, lat, lng, name, (6371 * acos(cos(radians('%s')) * cos(radians(lat)) * cos(radians(lng) - radians ('%s')) + sin(radians('%s')) * sin(radians(lat)))) AS distance FROM stations HAVING distance < '%s' ORDER BY distance LIMIT 0, 50",
mysqli_real_escape_string($link, $myLat),
mysqli_real_escape_string($link, $myLng),
mysqli_real_escape_string($link,$myLat),
mysqli_real_escape_string($link, $calcDistance));
$result = mysqli_query($link, $query);
$row_cnt = mysqli_num_rows($result);
if(!$result) {
die("Invalid query: " . mysqli_error());
}
header("content-type: application/json; charset=utf-8");
$items = array();
//iterate through the rows,
while($row = mysqli_fetch_assoc($result)) {
$items[] = $row;
}
echo json_encode($items); // this can immediatly be read by javascript
exit;
?>
You can add links/buttons, whith something like
<div onclick="searchNearLocations(50.80, 4.35, 20)">click: 20 km radius from (50.80, 4.35)</div>
To add the position of the client, check out my answer here
google getLocation function not work in my script
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