How do I pass a json object from one function to another? - javascript

I have a jquery function which via a php file, retrieves latitude and longitude from a database. In the same js file, I have a function that places markers on a Google map. I want to use the json(lat and long) returned by the first function, in the Google maps add marker function. Currently in my code below, ..the json data is simply displayed in an empty div. Is there some way to access that json data between functions, or can I combine the two functions somehow?
// Google Map
var map;
// markers for map
var markers = [];
// initialize the map
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 37.09024, lng: -95.712891},
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 4
});
}
// add markers
function addMarker(data) {
// get lat and long from data(json object)
var myLatlng = new google.maps.LatLng(parseFloat(data.latitude), parseFloat(data.longitude));
// custom marker image
//var image = "../img/infoblue.png";
// new marker
var marker = new MarkerWithLabel({
position: myLatlng,
map: map,
labelClass: "label",
labelContent: data.name,
labelAnchor: new google.maps.Point(20,0),
});
// add marker to array
markers.push(marker);
}
// this function gets json and then displays in a div on an html page
$(document).ready(function(){
$('.airport_form').submit(function(){
// show that something is loading
$('#response').html("<b>Loading response...</b>");
$.ajax({
type: "post",
dataType: "json",
url: "response.php",
data: $(this).serialize()
})
.done(function(data){
// show the response
$('#response').html("Name -> " + data.name + "<br>" + " Iata code -> " + data.iata + "<br>" + " Lat. -> " + data.latitude + "<br>" + " Longitude -> " + data.longitude);
})
.fail(function() {
// just in case posting the form fails
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
});

you can add your addMarker function to your done function like so ...
.done(function(data){
// add marker from data
addMarker(data);
// show the response
$('#response').html("Name -> " + data.name + "<br>" + " Iata code -> " + data.iata + "<br>" + " Lat. -> " + data.latitude + "<br>" + " Longitude -> " + data.longitude);
})

Related

Marker cluster Group

I have this code that gets the data from postgis and but when launching my page my markers won't show, even though there is no error in the console. the problem seemes to come from couche.on('data:loaded', function (e) since apparently it's not able to get the loaded data and because when i do couche.addTo(maCarte) directly the markers show. And i tried it in a another example with var couche = new L.GeoJSON.AJAX("data/markers.geojson", { and it works.
Another problem is when i enter a variable to select a specefic marker i always get the same error Uncaught SyntaxError: Unexpected token < in JSON at position 2 even though i checked my php file and it's fine and show the results when i launched directly Exécution du script PHP it happens in this code only when i add a variable and when there is none and the variable is null, the data is downloaded without any problem, so i don't know where the problem is coming from.
Can anyone please help me find a solution ?
function loadData() {
console.log('php/lecture.php?var=' + variable )
$.ajax({url:'php/lecture.php?var=' + variable ,
success: function(response){
data = JSON.parse(response)
console.log(data)
console.log('Données téléchargées : ' + response.length / 1000000 + 'Mo')
drawEntities(data)
maCarte.fitBounds(couche.getBounds())
}
})
}
couche = new L.GeoJSON(data.features, {
onEachFeature: function (feature, layer) {
layer.bindPopup('<h4>date_debut: ' + feature.properties.date_debut+
'</h4>')
},
pointToLayer: createCircleMarker
});
couche.on('data:loaded', function (e){
function makeGroup(color) {
return new L.MarkerClusterGroup({
iconCreateFunction: function(cluster) {
return new L.DivIcon({
iconSize: [20, 20],
html: '<div style="text-align:center;background:'+color + '">' +
cluster.getChildCount() + '</div>'
});
}
}).addTo(maCarte);
}
var groups = {
TR: makeGroup('red'),
DE: makeGroup('green'),
CA: makeGroup('orange'),
CO: makeGroup('blue')
};
e.target.eachLayer(function(layer) {
groups[layer.feature.properties.type].addLayer(layer);
});
});
}

Google map and places api exceeded your request quota for this API

i have create website on 000webhost. i use map on it and create new google api key but issue is that when i hit the api for first time through message exceeded your 'request quota for this API' how ever i never hit it before i hit the api for the first time with new api key. this is my php script.i need help
function initMap() {
var map = new google.maps.Map(document.getElementById('show_map'), {
center: {lat: 33.6518, lng: 73.1566},
zoom: 13
});
var input = document.getElementById('shopadd');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'pk'}
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
// Bind the map's bounds (viewport) property to the autocomplete object,
// so that the autocomplete requests use the current map bounds for the
// bounds option in the request.
autocomplete.bindTo('bounds', map);
// Set the data fields to return when the user selects a place.
autocomplete.setFields(['address_components', 'geometry', 'name']);
autocomplete.setOptions({strictBounds: true});
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
return;
}
var location = "Address " + place.formatted_address;
location += "Latitude " + place.geometry.location.lat();
location += "Longitude " + place.geometry.location.lng();
var lat = place.geometry.location.lat();
document.getElementById('lat').value = lat;
var lng = place.geometry.location.lng();
document.getElementById('lng').value = lng;
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var add = '';
if (place.address_components.length>0) {
add = add.concat(
(place.address_components[0] && place.address_components[0].short_name || ''),' ',
(place.address_components[1] && place.address_components[1].short_name || ''),' ',
(place.address_components[2] && place.address_components[2].short_name || ''),' ');
}
document.getElementById('add').value = add;
infowindowContent.children['place-icon'].src = place.icon;
infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = add;
infowindow.open(map, marker);
});
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key="my key"&libraries=places&callback=initMap" async defer></script>
Google changed their pricing model. The new plan gives you more flexibility and control over how you use our APIs. You can use as much or as little as you need and only pay for what you use each month.
As of July 16, 2018:
The Google Maps Platform APIs are billed by SKU.
Usage is tracked for each Product SKU, and an API may have more than one Product SKU.
Cost is calculated by: SKU Usage x Price per each use.
For each billing account, for qualifying Google Maps Platform SKUs, a $200 USD Google Maps Platform credit is available each month, and automatically applied to the qualifying SKUs.
For more information, visit this Link

Undefined variable when passing javascript variable to PHP with AJAX

I am trying to build a simple mobile app that checks database and gives user the correct venue based on their location. Essentially, I have two files: one with geolocation, JavaScript and AJAX call, and another one with php that checks the database and sends the correct result back. Everything on its own is working perfectly fine, but when I try to send geolocation coordinates to PHP it returns undefined. Why does it not pick up the coordinates (they pop up in a separate window)? How can I fix it?
Here is my geolocation and AJAX code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$( document ).ready(function() {
var latitude;
var longitude;
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by this browser");
}
function displayPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
var request = $.ajax({
url: "http://cs11ks.icsnewmedia.net/mobilemedia/ajax.php?latitude=" + latitude + "&longitude=" + longitude,
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#ajax").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
</script>
And here is the bit of PHP that handles these variables:
if (isset($_GET['latitude']) && isset($_GET['longitude'])) {
$latitude = $_GET['latitude'];
$longitude = $_GET['longitude'];
echo "Geolocation seems to work...";
echo $latitude;
echo $longitude;
//continue here
}else{
echo "Hello. I am your geolocation and I am not working.";
}
What I get is "Geolocation seems to work...undefinedundefined"
The Geolocation API is asynchronous, so you have to wait for the result to return
function displayPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
url : "http://cs11ks.icsnewmedia.net/mobilemedia/ajax.php",
data : {latitude : latitude, longitude : longitude},
type : "GET",
dataType : "html"
}).done(function(msg) {
$("#ajax").html(msg);
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
function displayPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}
remove var in both variable. Those two are not visible outside displayPosition. When you use the $.ajax call you're using latitude and longitude declared right under the $(document).raedy() but you never assign nothing to them so they're undefined.
Hope this solve your issue.
P.S. You se the values in the alert because you're using ones from position, not from your variables.
Do not use var inside your displayPosition function. You do not want to declare new variables inside the scope of the function, you want to assign values to the existing variables you declared in the global scope earlier.

JS: How to make a dynamic Google Maps Polyline?

I am working on a Google Map which needs to show:
a KML (floor-plan)
a Polyline which should take its coordinates from a GET response, each 5 seconds.
I would like the polyline to update itself with the new coordinates that arrives from the RESTful API.
This is the code [updated]:
var FlightPath1 = []
$(document).ready(function() {
var BASE_URL = "https://its.navizon.com/api/v1/sites/" //Do not change this
SITE_ID = "1001" // Your site ID here
MAC_add = "00:1E:8F:92:D0:56" //Mac address of the device to track
USERNAME = "demo#navizon.com" // Your username
PASSWORD = "" // Your password
var Path1=new google.maps.Polyline({
path:FlightPath1,
strokeColor:"#F020FF",
strokeOpacity:0.8,
strokeWeight:2
});
// Send the request
jQuery.support.cors = true; // Enable cross-site scripting
function makeCall() {
$.ajax({
type: "GET",
url: BASE_URL + SITE_ID + "/stations/" + MAC_add + "/",
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", "Basic " + Base64.encode(USERNAME + ":" + PASSWORD));
},
success: function(jimmi) {
// Output the results
if (typeof jimmi === "string") {
jimmi = JSON.parse(jimmi);
}
//Display the results
FlightPath1.push("new google.maps.LatLng(" + jimmi.loc.lat + "," + jimmi.loc.lng + "),");
var mapOptions = {
zoom: 19,
center: new google.maps.LatLng(jimmi.loc.lat,jimmi.loc.lng),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var SanDiegoKML = new google.maps.KmlLayer({
url: 'https://s3.amazonaws.com/navizon.its.fp/1001/05w0kyw829_a.kml'
});
SanDiegoKML.setMap(map);
google.maps.event.addDomListener(window, 'load', jimmi);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error');
}
});
window.setTimeout(makeCall, 5000); //run the script each 5000 milliseconds
}
makeCall();
})
But I nothing happens. And I get no errors neither.
Could some one help me?
Thanks..
Two issues:
The necessary var, Path1 is internal and private to initialize(), therefore out of scope with regard to the ajax success function which is in an entirely different scope.
The ajax success function does nothing other than to push a string derived from the response onto an array. Doing so will not, in itself, affect the polyline.
Fix (1) first, then (2).

JQuery $.each returning same data set twice

I'm building an Instagram mapping app and I'm trying to iterate through the returned JSON using $.each. I'm currently testing it by returning the coordinates of the picture into a <div>. It's working wonderfully, except the same data shows up twice. Here is the statement (the commented-out code is for putting it on the map):
$.each(photos.data, function (index, photo) {
if (photo.location) {
/* var photocoords = google.maps.LatLng(photo.location.latitude,location.longitude);
var marker = new google.maps.Marker({
position: photocoords,
map: map,
title: 'Test'
});//end new marker
*/
photo = photo.location.latitude + ' , ' + photo.location.longitude + '<br>';
$('#photos-wrap').append(photo);
} //end if
else {
return true
}
});
And the data it's returning:
38.9232268 , -77.0464289
35.046506242 , -90.025382579
35.189142533 , -101.987259233
38.9232268 , -77.0464289
35.046506242 , -90.025382579
35.189142533 , -101.987259233
Thanks for any help you can provide.
change your code to this one
var new_photo = photo.location.latitude + ' , ' + photo.location.longitude + '<br>';
$('#photos-wrap').append(new_photo);

Categories