Ajax call error after opening infowindow - php

I'm using gmap3 for google map on my site.
I locate a marker after click on a button. Everyclick will give me different location depend on what a user chooses.
It goes smooth, however, when the user click on the marker to open the info window, and close it, the ajax call doesn't work. It gives me this error on chrome console, "Uncaught TypeError: Cannot call method 'lat' of undefined" in main.js.
EDIT: it seems I forgot to put autofit{} from my code, and it seems this was the problem. Anyone know how to user autofit in this case?
Here is my code
// create a map
$('#map_canvas').gmap3({
map: {
options: {
center: [-2.899153, 117.722626],
zoom: 4,
mapTypeId: google.maps.MapTypeId.SATELLITE
}
}
});
$('.locate-btn').on('click', function() {
var place_id = $('.place').val();
var address = $('.address').val();
$.ajax({
url: 'ajax.php',
type: 'post',
dataType: 'json',
data: 'place_id=' + place_id + '&address=' + address,
beforeSend: function() {
$('.loading').append("<img src='/images/loading.gif' id='loader' />");
},
success: function(place) {
$('#map_canvas').gmap3({
marker: {
latLng: [place.lat, place.lng],
data: 'nearest hotels<a class="btn btn-danger" href="#">about</a>',
events: {
click: function(marker, event, context) {
var map = $(this).gmap3('get'),
infowindow = $(this).gmap3({
get: {
name: 'infowindow'
}
});
if (infowindow) {
infowindow.close();
infowindow.open(map, marker);
infowindow.setContent(context.data);
} else {
$(this).gmap3({
infowindow: {
anchor: marker,
options: {
content: context.data
}
}
});
}
}
}
},
autofit: {}
});
}
});
});
});
Would anyone tell what's wrong?
Thank you.

Related

"calendar.refetchEvents();" not refreshing events

I am using fullcalendar v4 (https://fullcalendar.io/) and I am trying to delete events when the event is clicked.
When I click on an event, I have this code to delete the event:
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
locale: 'pt',
plugins: [ 'interaction', 'dayGrid', 'timeGrid', 'list' ],
editable: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
},
// CUSTOM CODE DATABASE
events: load.php,
eventClick:function(clickedInfo)
{
if(confirm("Are you sure you want to delete this event?"))
{
var id = clickedInfo.event.id;
$.ajax({
url:"delete.php",
type:"POST",
data:{id:id},
success: function() {
alert('Deleted!');
calendar.refetchEvents();
}
})
}
},
});
calendar.render();
});
The event is getting deleted in the database, so the function works fine, but the events don't refresh and the deleted event is still showing in the calendar. It only disappears when I fully refresh the page, which is not ideal.
Any idea why?
It doesn't look like the calendar object is ever being initialized.
I would try changing your event listener as described in the documentation:
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'dayGrid' ]
});
calendar.render();
});
Ref. https://fullcalendar.io/docs/initialize-globals
I am assuming you are using script tags, but if you're using a build system (i.e. webpack), then you can try this: https://fullcalendar.io/docs/initialize-es6
For removing an event, I would just try this:
eventClick:function(clickedInfo)
{
if(confirm("Are you sure you want to delete this event?"))
{
var id = clickedInfo.event.id;
$.ajax({
url:"delete.php",
type:"POST",
data:{id:id},
success: function() {
alert('Deleted!');
//calendar.refetchEvents(); // remove this
clickedInfo.event.remove(); // try this instead
}
})
}
},
Ref. https://fullcalendar.io/docs/Event-remove

Google maps API.

I have a map on my site
There are lots of markers with infoWindows on this map.
For each infoWindow i use custom blade
in result, on page init DOM take to much time to load, if there are too many markers on map.
I have and idea to load this windows only on marker click.
Can somebody help me with that?
try the below code:
function makeInfoWindowEvent(map, infowindow, marker) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
Found a good solution for this situation. Maybe it will be useful for somebody.
On get all
var locations = [
#if(count($trainings) > 0)
#foreach($trainingsas $item)
#if($item->p_lat && $item->p_lng)
{
lat: {{$item->p_lat}},
lng: {{$item->p_lng}},
id: {{ $item->p_id }}
},
#endif
#endforeach
#endif
];
Than, on mapping all marker on map, add a listener for each marker
google.maps.event.addListener(marker, 'click', function (evt) {
var id = marker.get("id");
$.ajax({
url: "{{ route('getInfoWindow') }}",
data:{
id: id
},
success: function(data) {
console.log(data);
infoWin.setContent(data);
infoWin.open(map, marker);
}
});
That is all we need. On backend we get model with that it and render output with our view!

Google charts draw same chart multiple times

i'm trying to make a modal dialog in html, and when something is pressed to draw a google chart in the modal.
function inter(id)
{
var arr = [['Album','Vizualizari']];
$.ajax({
url: 'popular.php',
type: 'GET',
dataType: 'json',
success: function (json) {
$.each(json,function (i ,value )
{
var c =[value.title, value.popular];
arr.push(c);
});
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
google.visualization
var data = new google.visualization.arrayToDataTable(arr);
var options = {
title: 'Chess opening moves',
width: 800,
legend: { position: 'none' },
bars: 'vertical', // Required for Material Bar Charts.
axes: {
y: {
0: { side: 'top', label: 'Percentage'} // Top x-axis.
}
},
bar: { groupWidth: "100%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
chart.draw(data, options);
};
}});
}
It worked but only on first modal. When i try to open another modal i've got the follow error : google.charts.load() cannot be called more than once . How can i draw the chart using another callback, not 'setOnLoadCallback' ?
Your problem is that your function contain these two lines :
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
This is wrong. google.charts.load() loads the google visualization API and setOnLoadCallback() is executed once when the API has finished loading. But you do not want to show the chart when google visualization is loaded, but when the user click a button (or whatever) to show a modal. So remove setOnLoadCallback completely and move load() out to the global scope - simply call drawStuff() manually from the success handler :
google.charts.load('current', {'packages':['bar']});
function inter(id) {
var arr = [
['Album', 'Vizualizari']
];
$.ajax({
url: 'popular.php',
type: 'GET',
dataType: 'json',
success: function(json) {
$.each(json, function(i, value) {
var c = [value.title, value.popular];
arr.push(c);
});
drawStuff(arr);
})
})
function drawStuff(arr) {
var data = new google.visualization.arrayToDataTable(arr);
var options = {
title: 'Chess opening moves',
width: 800,
legend: {
position: 'none'
},
bars: 'vertical', // Required for Material Bar Charts.
axes: {
y: {
0: {
side: 'top',
label: 'Percentage'
} // Top x-axis.
}
},
bar: {
groupWidth: "100%"
}
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
chart.draw(data, options);
}
}

Google Maps - how to update markers / positions to existing map using ajax/PHP?

I have a working Google Map on my site using Google Maps API v3.
The map is loaded on pageload and applied with multiple markers/positions from an array of coordinates.
Now, what I want to do is to dynamically update the markers/positions with a new array of coordinates with an ajax call.
Here is an example of my markup:
<div id="map-canvas"></div>
<script type="text/javascript">
var LocationData = <?php echo $coordsarray; ?>;
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 10,
draggable: true
} );
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (var i in LocationData)
{
var p = LocationData[i];
var latlng = new google.maps.LatLng(p[0], p[1]);
bounds.extend(latlng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: p[2]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.title);
infowindow.open(map, this);
});
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
//Ajax call
var interval = 5000; // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
jQuery.ajax({
type: 'POST',
url: '/codes/LiveVisitsStats/postlivecounter.php',
dataType : 'html',
success: function (data) {
var arr = data.split('|');
jQuery('#counterint').html(arr[0]);
jQuery('#extrainfoscounter').html(arr[1]);
},
complete: function (data) {
// Schedule the next
setTimeout(doAjax, interval);
}
});
}
setTimeout(doAjax, interval);
</script>
So what I now need to do is to send an array of coordinated via the Ajax call and on success update the existing Google Map with new coordinates.
I have tried to find a documentation of this but no luck..
If someone knows a good way to do this please help.
I ended up choosing a completely different approach. Here is the code I used, which works
<script type="text/javascript">
var locations = {}; //A repository for markers (and the data from which they were contructed).
//initial dataset for markers
var locs = {
1: {
info: '11111. Some random info here',
lat: -37.8139,
lng: 144.9634
},
2: {
info: '22222. Some random info here',
lat: 46.0553,
lng: 14.5144
},
3: {
info: '33333. Some random info here',
lat: -33.7333,
lng: 151.0833
},
4: {
info: '44444. Some random info here',
lat: 27.9798,
lng: -81.731
}
};
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 1,
maxZoom: 8,
minZoom: 1,
streetViewControl: false,
center: new google.maps.LatLng(30, 30),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
function setMarkers(locObj) {
jQuery.each(locObj, function (key, loc) {
if (!locations[key] && loc.lat !== undefined && loc.lng !== undefined) {
//Marker has not yet been made (and there's enough data to create one).
//Create marker
loc.marker = new google.maps.Marker({
position: new google.maps.LatLng(loc.lat, loc.lng),
map: map
});
//Attach click listener to marker
google.maps.event.addListener(loc.marker, 'click', (function (key) {
return function () {
infowindow.setContent(locations[key].info);
infowindow.open(map, locations[key].marker);
}
})(key));
//Remember loc in the `locations` so its info can be displayed and so its marker can be deleted.
locations[key] = loc;
} else if (locations[key] && loc.remove) {
//Remove marker from map
if (locations[key].marker) {
locations[key].marker.setMap(null);
}
//Remove element from `locations`
delete locations[key];
} else if (locations[key]) {
//Update the previous data object with the latest data.
jQuery.extend(locations[key], loc);
if (loc.lat !== undefined && loc.lng !== undefined) {
//Update marker position (maybe not necessary but doesn't hurt).
locations[key].marker.setPosition(
new google.maps.LatLng(loc.lat, loc.lng));
}
//locations[key].info looks after itself.
}
});
}
setMarkers(locs); //Create markers from the initial dataset served with the document.
//ajaxObj.get(); //Start the get cycle.
// *******************
//Ajax code
var interval = 5000; // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
jQuery.ajax({
type: 'POST',
url: '/codes/LiveVisitsStats/postlivecounter.php',
dataType : 'html',
success: function (data) {
var arr = data.split('|');
jQuery('#counterint').html(arr[0]);
jQuery('#extrainfoscounter').html(arr[1]);
jQuery('#testdiv').html(arr[2]);
//test: simulated ajax
var testLocs = {
1: {
info: '1. New Random info and new position',
lat: -37,
lng: 124.9634
},
2: {
lat: 70,
lng: 14.5144
},
3: {
info: '3. New Random info'
},
4: {
remove: true
},
5: {
info: '55555. Added',
lat: -37,
lng: 0
}
};
setMarkers(testLocs);
},
complete: function (data) {
// Schedule the next
setTimeout(doAjax, interval);
}
});
}
setTimeout(doAjax, interval);
</script>

google maps api v3 doesn't work while retrieving string data with AJAX

I'm trying to place some markers on a map retrieving thier STRING address from a PHP document by an AJAX call (the PHP connects to a database and takes the data to reply to the AJAX call). Here's the JQuery/JS code:
function chiamaAJAX(idCli) {
$.ajax({
type: "GET",
url: "scaricaContatti.php",
data: "idCli="+idCli,
dataType: "text",
success: function(msg){
codeAddress(msg);
},
error: function(){
alert("Chiamata fallita!!!");
}
});
}
function initialize() {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
var mapProp = {
center:new google.maps.LatLng(51.165691,10.451526),
zoom:6,
mapTypeId:google.maps.MapTypeId.HYBRID
};
map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
function codeAddress(address) {
alert('CODEADDRESS:' +address);
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Now the problem is I can't make the geocode call work, the status returns always 'INVALID_REQUEST' (it means that the address is not in the right format) but if I place the full string of the address instead of the 'address' variable it works without problems...this makes me think that the datatype returning from the AJAX call is not good to be passed to geocode function, maybe it needs to be converted? How? Thanks a lot! Daniele

Categories