Dynamic ajax content for InfoWindow in Google maps - javascript

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');
}
?>

Related

Sending AJAX response to Google Maps location markers with JSON

Upon clicking a button, an AJAX response is called to output JSON based on a search query. I would like to use the variable all_locations from the AJAX response, to output into the Google map markers. Not too sure how this can be done. I researched into using async as false but to no success.
Form
<form id="filter">
<span class="ek-search-address col-xs-8">
<label for="address">Location</label>
<input id="address" name="property_location" value="New York" placeholder="Input Address" type="text"/>
</span>
<span class="ek-search-radius live-search col-xs">
<select id="radius_km">
<option value=1>1km</option>
<option value=2>2km</option>
<option value=5>5km</option>
<option value=30>30km</option>
</select>
</span>
<button onClick="showCloseLocations()">Search</button>
<input type="hidden" name="action" value="ek_search">
</form>
<div id="map_canvas">
AJAX call
jQuery(function($){
$('#filter').submit(function(){
var filter = $('#filter');
var ajaxurl = '<?php echo admin_url("admin-ajax.php", null); ?>';
data = { action: "ek_search"};
var all_locations = $.ajax({
url: ajaxurl,
data:data,
async:false,
type: 'POST', // POST
dataType: 'json',
success: function(response) {
console.log(response);
}
});
return false;
});
});
map.js
jQuery(function($) {
var map = null;
var radius_circle;
var markers_on_map = [];
var geocoder;
var infowindow;
new google.maps.places.Autocomplete(
(document.getElementById('address')), {
types: ['geocode']
});
//initialize map on document ready
$(document).ready(function() {
var latlng = new google.maps.LatLng(50.927978, -5.408908);
var myOptions = {
zoom: 17,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
google.maps.event.addListener(map, 'click', function() {
if (infowindow) {
infowindow.setMap(null);
infowindow = null;
}
});
});
function showCloseLocations() {
var i;
var radius_km = $('#radius_km').val();
var address = $('#address').val();
//remove all radii and markers from map before displaying new ones
if (radius_circle) {
radius_circle.setMap(null);
radius_circle = null;
}
for (i = 0; i < markers_on_map.length; i++) {
if (markers_on_map[i]) {
markers_on_map[i].setMap(null);
markers_on_map[i] = null;
}
}
if (geocoder) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
var address_lat_lng = results[0].geometry.location;
radius_circle = new google.maps.Circle({
center: address_lat_lng,
radius: radius_km * 1000,
clickable: false,
map: map
});
if (radius_circle) map.fitBounds(radius_circle.getBounds());
for (var j = 0; j < all_locations.length; j++) {
(function(location) {
var marker_lat_lng = new google.maps.LatLng(location.lat, location.lng);
var distance_from_location = google.maps.geometry.spherical.computeDistanceBetween(address_lat_lng, marker_lat_lng); //distance in meters between your location and the marker
if (distance_from_location <= radius_km * 1000) {
var new_marker = new google.maps.Marker({
position: marker_lat_lng,
map: map,
title: location.name
});
google.maps.event.addListener(new_marker, 'click', function() {
if (infowindow) {
infowindow.setMap(null);
infowindow = null;
}
infowindow = new google.maps.InfoWindow({
content: '<div style="color:red">' + location.name + '</div>' + " is " + distance_from_location + " meters from my location",
size: new google.maps.Size(150, 50),
pixelOffset: new google.maps.Size(0, -30),
position: marker_lat_lng,
map: map
});
});
markers_on_map.push(new_marker);
}
})(all_locations[j]);
}
} else {
alert("No results found while geocoding!");
}
} else {
alert("Geocode was not successful: " + status);
}
});
}
}
});
Ajax is an asynchronous process, so you need to send all locations as an parameter inside success callback function
Try this:
Ajax:
jQuery(function($){
$('#filter').submit(function(e){
e.preventDefault();//preventing form to submit with page reload
var filter = $('#filter');
var ajaxurl = '<?php echo admin_url("admin-ajax.php", null); ?>';
data = { action: "ek_search"};
$.ajax({
url: ajaxurl,
data:data,
async:false,
type: 'POST', // POST
dataType: 'json',
success: function(response) {
console.log(response);
showCloseLocations(response.all_locations);
}
});
return false;
});
});
Update function showCloseLocations to accept all_locations as parameter
function showCloseLocations(all_locations) {
//show location function code here
}
Question: I would like to know how you are submitting your form with #filter? because there is no submit type button in your html, make sure to change type of search button to submit instead of button so that first form can submit with search input to get all locations
<button type="submit">Search</button>

Laravel and Geocoding markers (nearby users) do not update correctly

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.

Geocoding by extracting location from MySQL via PHP

I have written the following PHP script to get the value from MySQL database:
<?php
$user="root";
$password="password";
$dbh = new PDO("mysql:host=localhost;dbname=muzicmap", $user, $password);
$sql = "SELECT DISTINCT (
`name`
) AS `name` , `id` , `location` , `background` , `genre` , `current_members` , `website` , `image` , `lonlat`
FROM `artist`
WHERE `location` LIKE '%Los Angeles%'
LIMIT 10
";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//To output as-is json data result
//header('Content-type: application/json');
//echo json_encode($result);
//Or if you need to edit/manipulate the result before output
foreach ($result as $row){
$return[]=array('id' => $row['id'],'name'=>$row['name'],'location'=> $row['location'],'background' => $row['background'], 'genre' => $row['genre'],'current_members'=>$row['current_members'],'website' => $row['website']);
}
$dbh = null;
header('Content-type: application/json');
echo json_encode($return);
?>
Now I have made a page in which I want to achieve 3 things:
1. Geocode the location in the location field of my json.
2. Put markers on google maps.
3. Make a drawable type object after doing this all.
So I wrote the following:
markers= []
var geocoder;
function initialize() {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(40.2859268188,-75.9843826294)
}
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.CIRCLE,
]
},
circleOptions: {
fillColor: '#FFFF00',
fillOpacity: 0,
strokeWeight: 1,
clickable: false,
editable: true,
zIndex: 1
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'circlecomplete', function(circle) {
var IDs=[];
for(var k in markers){
if(google.maps.geometry.spherical
.computeDistanceBetween(circle.getCenter(),markers[k].getPosition())
<=circle.getRadius()){
IDs.push(k);
}
}
});
$(function ()
{
$.ajax({
url: 'jsonTest.php', //the script to call to get data
data: "",
dataType: 'json',
success: function(data)
{
adMarker(map, data);
}
});
});
}
function adMarker(map,json1){
geocoder= new google.maps.Geocoder();
for (var i = 0; i < (json1.length); i++) {
geocoder.geocode({'address':json1[i]['location']},function(results,status){
if (status == google.maps.GeocoderStatus.OK){
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: json1[i]['names'],
zIndex: json1[i]['id']
});
markers.push(marker);
}else {
alert("Something wrong");
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
I am not getting the desired result where the markers are put on the map after geocoding. When I debug it I see that the code snipet which is supposed to geocode and create the marker is not run in the for iteration. Why is that? I am new to javascript I would really appreciate all the help fixing this.
The error in the debugger though,says:
InvalidValueError: setZIndex: not a number
I solved the problem.
Because there is an asynchronous call in the adMarker(). I made a function so that copies of that function are made on each for iteration as the asynchronous call will run only after the iteration is complete. This way all the iteration with copies will run. Updated code:
function adMarker(map,json1){
geocoder= new google.maps.Geocoder();
for (var i = 0; i < (json1.length); i++) {
abc(i, json1, map);
}
}
function abc (index, json1, map){
var current_index = index;
geocoder.geocode({'address':json1[index]['location']},function(results,status){
if (status == google.maps.GeocoderStatus.OK){
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: json1[index]['names'],
zIndex: parseInt(json1[index]['id'])
});
markers.push(marker);
}else {
alert("Something wrong");
}
});
}

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

Categories