Trouble Adding Markers to Google Maps via Ajax - ajax

What I am trying to achieve:
Generate Map
Get Bounds information for Map
Make Ajax call passing Bounds information, data returned is Marker info
Populate Map with Markers
I am stuck because I cannot get the Ajax call to trigger.
The code seems to stop running after the alert("ajax ready"). I have a breakpoint on my controller action which never gets hit.
The only error I am getting is that "nE is undefined", however if I put in an alert the line after I am setting the value, then the the value is shown, so am not even sure that is relevant.
I have worked successfully with an earlier version of Google Maps, V3 seems a bit different. I couldn't get the lines of code to set the bounds to run until they were placed in an event listener. I tried the same with the Ajax call but doesn't make a difference.
I do know that I am not adding the markers to the map within the ajax call, I have yet to get to that part.
Javascript:
function initMap() {
var markers = [];
var map = new google.maps.Map(document.getElementById('local-map'), {
center: { lat: 51.509865, lng: -0.118092 },
zoom: 15
});
var bounds = undefined;
var nE = undefined;
var sW = undefined;
google.maps.event.addListener(map, 'bounds_changed', function () {
bounds = map.getBounds();
nE = bounds.getNorthEast();
sW = bounds.getSouthWest();
});
alert("ajax ready");
$.ajax({
type: "POST",
url: '/Home/GetMapMarkers',
data: { neLatitude: nE.lat(), neLongitude: ne.lng(), swLatitude: sW.lat(), swLongitude: sW.lng() }
}).done(function (data) {
for (i = 0; i < data.length; i++)
{
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i].Latitude, data[i].Longitude),
map: map,
title: data[i].RestaurantName
});
markers.push(marker);
}
});
}

The "bounds_changed" listener will fire asynchronously when the map bounds changes. You need to put your AJAX call inside its callback function (when/where the new bounds is available):
google.maps.event.addListener(map, 'bounds_changed', function () {
bounds = map.getBounds();
nE = bounds.getNorthEast();
sW = bounds.getSouthWest();
alert("ajax ready");
$.ajax({
type: "POST",
url: '/Home/GetMapMarkers',
data: { neLatitude: nE.lat(), neLongitude: ne.lng(), swLatitude: sW.lat(), swLongitude: sW.lng() }
}).done(function (data) {
for (i = 0; i < data.length; i++)
{
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i].Latitude, data[i].Longitude),
map: map,
title: data[i].RestaurantName
});
markers.push(marker);
}
});
});

Related

admin-ajax.php do not recognizes 'action'. $_REQUEST is empty

After two days of fruitless research, I decided to join the community. I hope to get a solution. I develop a plug-in that, among other things, must implement the upload of documents. this should be done using ajax technology. the problem is that the request is approved, but admin_ajax.php reacts like no action was taken. Outside of wp this piece of code works fine, as it was thought out. The problems come with installing this code in wp. Below is my code
PHP. This code in the main class that will call from main modul of plugin
class main{
//other activation methods
private function register_scripts(){
add_action('wp_enqueue_scripts', array($this,'re_add_script'));
}
public function re_add_script() {
wp_enqueue_script('re_upload',plugins_url('re'.'/js/re_upload.js'),array('jquery'));
wp_localize_script('re_upload',"re_ajax",array(
'ajaxurl'=>admin_url("admin-ajax.php")));
add_action( 'wp_ajax_upload', 'processingUpload');
}
}//end of class
//callback function
function processingUpload(){
$clsUpload = new UploadsDocs();
$clsUpload->setRequestedData($_FILES,$_POST['doc_id']);
$clsUpload->checkUploadsFiles();
$clsUpload->outputFilesList();
wp_die();
}
jQuery 're_upload.js'
jQuery(document).ready(function (e) {
jQuery('#bt_upload').on('click', function () {
var toUpload=getFileListToUpload();
var form_data = new FormData();
var ins = input.files.length;
for (var x = 0; x < ins; x++) {
if (isFileToUpload(input.files[x],toUpload)){
form_data.append("files[]", input.files[x]);
}
}
form_data.append("doc_id", jQuery('#doc_id')[0].value);
var data_to_sent={
action: 'upload',
datas: form_data
};
jQuery.ajax({
url: re_ajax.ajaxurl, // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: data_to_sent,
type: 'post',
success: function (response) {
// do something
},
error: function (response) {
// do something
},
xhr: function(){
//upload Progress
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//update progressbar
jQuery('#bt_upload').css("display","none");
jQuery('#progress-wrp').css("display","block");
jQuery('#progress-wrp' +" .progress-bar").css("width", + percent +"%");
(percent<50)? jQuery('#progress-status').addClass('status-less-then-50'): jQuery('.status-less-then-50').removeClass('status-less-then-50').addClass('status-more-then-50');
jQuery('#progress-status').text("Uploading..."+percent +"%");
}, true);
}
return xhr;
},
mimeType:"multipart/form-data"
});
});
});
function getFileListToUpload(){
var list=[];
var elem = document.getElementsByClassName('preview');
var tag_li=elem[0].querySelectorAll('p');
for (var i=0;i<tag_li.length;i++){
list[i]=tag_li[i].textContent.split('(')[0];
}
return list;
}
function isFileToUpload(input_file,files_toUpload){
var res=false;
for(var i=0; i<files_toUpload.length;i++){
if (input_file.name==files_toUpload[i]){
res=true;
break;
}
}
return res;
}
The problem is
add_action( 'wp_ajax_upload', 'processingUpload');
is not called.
The upload is done in two separate invocations of the server. The first invocation displays the upload page to the user. The second invocation processes the AJAX request. Your call to
add_action( 'wp_ajax_upload', 'processingUpload');
is done in the first invocation where it is not needed but not in the second invocation where it is needed.
Please read https://codex.wordpress.org/AJAX_in_Plugins. (Observe carefully how the call to 'add_action( 'wp_ajax_...', ...) is done.) Further, you need to read about nonces.
Try to append action to your ajax url like:
url: re_ajax.ajaxurl?action=upload
and
data: form_data
or pass it to form_data like:
form_data.append('action', 'upload')

Ajax Request with Googlemap API

I'm building a page that will display a Googlemap with markers. Since I have about 50000 markers, I decided not to load them all at once.
Therefore I tried building an JSON request to my server (see code below) but here is my problem:
When I use the code as it is presented here, the Map is blank (no Map shows up).
When I remove the $.ajax and leave the function getMarkers emtpy, the map shows properly (whitout marker of course).
Can anyone tell me what I'm doing wrong please?!
Thank you!
(If that is any help, I'm using Django)
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function init_map() {
var mapOptions = {
center: new google.maps.LatLng(48.853,2.35),
zoom: 6,
streetViewControl: false,
};
var myMap = new google.maps.Map(document.getElementById("map-container"),mapOptions);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(myMap, 'idle', getMarkers);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
}
}
google.maps.event.addDomListener(window, 'load', init_map);
function getMarkers() {
$.ajax({
type: 'POST',
url: {%url 'pointslink'%},
async: "true",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(
coords: myMap.getBounds(),
zoom: myMmap.getZoom()
),
success: updateMarkers
});
}
function updateMarkers(data) {
{% for city in data %}
var pos = new google.maps.LatLng({{city.latitude}},{{city.longitude}});
var marker = new google.maps.Marker({
position: pos,
map: myMap,
title:'{{city.name}}'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('Name: {{city.name}}<br/>Population: {{city.population}}');
infowindow.open(myMap, this);
});
{%endfor%}
}
</script>

HighStocks not updating URL

I posted this question AJAX URL update as I thought the problem with my code was with AJAX but I think this could be an issue with HighStocks.
I have an external .js file with these functions:
//uses AJAX call to retrieve data and then creates the chart with the data
function createChart(ticker) {
$.ajax({
type: 'post',
url: 'http://...' + ticker + '....com',
success: function (data, status) {
//chart is rendered in here
}
//gets the user inputted ticker symbol from a HTML input box
// and passes to chart function
function getTicker() {
var ticker = document.getElementById('userInput').value;
createChart(ticker);
}
My HTML file just has a simple form with an input box and a button that when clicked calls the getTicker function. For some reason the chart is not being created and the AJAX call doesnt seem to work.
Is this something with HighStocks maybe? Any suggestions would be appreciated.
UPDATE Thank you for the suggestions, I have attempted to use JSONP but the chart still does not load. Can anybody see what I am doing wrong?
var closePrices = new Array();
var dateArray = new Array();
var timeStampArray = new Array();
var timeClose = new Array();
function jsonCallback(data, ticker) {
console.log( data );
//Put all the closing prices into an array and convert to floats
for(var i=0; i < data.query.results.quote.length; i++)
{
closePrices[i] = parseFloat( data.query.results.quote[i].Close );
}
//displays the values in the closePrices array
console.log( closePrices );
//Put all the dates into an array
for(var i=0; i < data.query.results.quote.length; i++)
{
dateArray[i] = data.query.results.quote[i].date;
}
//Convert all the dates into JS Timestamps
for(var i=0; i < dateArray.length; i++)
{
timeStampArray[i] = new Date( dateArray[i] ).getTime();
}
for(var i=0; i<data.query.results.quote.length; i++)
{
timeClose.push( [timeStampArray[i], closePrices[i]] );
}
timeClose = timeClose.reverse();
console.log ( timeClose );
//displays the dateArray
console.log( dateArray );
console.log( timeStampArray );
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : ticker + ' Stock Price'
},
series : [{
name : ticker,
data: timeClose,
tooltip: {
valueDecimals: 2
}
}]
});
}
function createChart() {
var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22' + ticker +'%22%20and%20startDate%20%3D%20%222013-01-01%22%20and%20endDate%20%3D%20%222013-02-25%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?';
//Ajax call retrieves the data from Yahoo! Finance API
$.ajax( url, {
dataType: "jsonp",
success: function(data, status){
console.log(status);
jsonCallback(data, ticker);
},
error: function( jqXHR, status, error ) {
console.log( 'Error: ' + error );
}
});
}
//Function to get ticker symbol from input box.
function getTicker() {
var ticker = document.getElementById('userInput').value;
createChart(ticker);
}
Thanks to Jeffrey Blake and Pawel Fus for your suggestions. Using JSONP I was able to get my program functioning correctly :)

Missing dynamic Markers GMaps V3

I have written some code to fetch zipcodes from a mysql db via ajax call, geocode them, then make markers out of them on a GMap. The markers are clickable to reveal some demographic data. It works if i leave the alert in the each loop uncommented. If not it only shows about 8 markers. Any and all help is appreciated. Relevant code:
function initialize() {
var geocoder = new google.maps.Geocoder();
var markers = [];
var latlng = new google.maps.LatLng("33.7463915", "-117.86044720000001");
var myOptions = {
zoom: 11,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$.ajax({
url: 'getzips.php',
dataType: 'json',
success: function (data) {
$.each(data.rows, function(i, item) {
//alert(item.zip);
if (geocoder) {
geocoder.geocode({ 'address': item.zip }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: item.zip
});
var infowindow = new google.maps.InfoWindow({
content: item.zip
});
google.maps.event.addListener(marker, "click", function() {
$.ajax({
url: 'getinfo.php?zipcode=' + marker.title,
success: function(data){
infowindow.setContent(data);
infowindow.open(map, marker);
}
});
});
markers.push(marker);
}
});
}
else
alert("geocode error");
});
}
});
//alert(markers.length);
}
Google Geocoding API has both query and rate limits. You need to slow down when querying.
Use of the Google Geocoding API is subject to a query limit of 2,500 geolocation requests per day.
Additionally, we enforce a request rate limit to prevent abuse of the service.

google maps call within a For Loop not returning distance

I am calling google maps within a for loop in my javascript as I have mulitple routes that need to be costed separately based on distances.
Everything works great except that the distance is only returned for one of the routes.
I have a feeling that it is something to do with the way I have the items declared within the ajax call for the maps. Any ideas what could be the issue from the code below?
for (var i = 1; i <= numJourneys; i++) {
var mapContainer = 'directionsMap' + i;
var directionContainer = $('#getDistance' + i);
$.ajax({
async: false,
type: "POST",
url: "Journey/LoadWayPoints",
data: "{'args': '" + i + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d != '[]') {
var map = new GMap2(document.getElementById(mapContainer));
var distance = directionContainer;
var wp = new Array();
//routes
var counter = 0;
$.each(content, function () {
wp[counter] = new GLatLng(this['Lat'], this['Long']);
counter = counter + 1;
});
map.clearOverlays();
map.setCenter(wp[0], 14);
// load directions
directions = new GDirections(map);
GEvent.addListener(directions, "load", function () {
alert(directions.getDistance());
//directionContainer.html(directions.getDistance().html);
});
directions.loadFromWaypoints(wp, { getSteps: true });
}
}
});
}
The issue was down to a non declared variable. Just before the GEvent call there is a variable called 'directions' but this was never actually declared with a var so it wasn't being cleared out.
var directions = new GDirections(map);
Doing the above worked for me.

Resources