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).
Related
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);
});
});
}
I understand that this question asked MANY times, but I can't figure out how to make it work in my circumstances
It is a simple thing. I have url = WWW, but opening it in web browser you will see JSON.
I need to use JavaScript to get this JSON from URL and use it further.
<script>
var data;
$.getJSON("http://XXX?callback=?").done(function( data ) {
console.log('hello', data);
data = data;
initMap();
});
function initMap() {
//response from URL have to be used here
data.forEach((item) => {
});
}
</script>
DOes anyone know how to solve it? Ideally by using ASYNC
This is FULL CODE:
<script>
// data from server
$.getJSON("http://XXX?callback=?").then(function( data ) {
console.log('hello', data);
initMap(data);
});
// place you want to initially center the map on
const center = {
lat: 51.509865,
lng: -0.118092
}
function initMap(data) {
// set up map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: center.lat, lng: center.lng}
});
// loop over data from server
data.forEach((item) => {
// build a infowindow add dump the product table into it.
var infowindow = new google.maps.InfoWindow({
content: item.Products
});
// add and position the marker on the map
var marker = new google.maps.Marker({
position: {lat: item.Latitude, lng: item.Longitude},
map: map,
title: item.StoreName
});
// and event for opening the infowindow
marker.addListener('click', function() {
infowindow.open(map, marker);
});
});
}
google.maps.event.addDomListener(window, 'load', initMap);
</script>
JSON Looks like this :
[
{
"LatLan": "-3,22",
"Latitude": 22,
"Longitude": -3,
"StoreName": "XXX",
"Products": "XXX"
},
// carry on...
]
data = data
This will not work as you expect.
I would recommend passing the data into your initMap method: initMap(data)
function initMap(data) {
//response from URL have to be used here
data.forEach((item) => {
});
}
You would be better using a construct like this so you're not using a global variable, that's frowned upon. using a top level global variable like data you could stomp on any other modules that are using a global data variable (they shouldn't be, but...). Also, the line data = data is not going to assign to the global data variable, since the data variable that's in scope is the one inside the done block (I changed it to then()).
$.getJSON("http://XXX?callback=?").then(function( data ) {
console.log('hello', data);
initMap(data);
});
function initMap(data) {
//response from URL have to be used here
data.forEach((item) => {
});
}
Here is one way to loop through JSON:
var tableRow = '';
$.ajax({
url: 'https://randomuser.me/api/?&results=50&inc=name,email',
method: 'GET',
success: function(data) {
var items = '';
for (var i = 0; i < data.results.length; i++) {
items += '<tr><td>' + data.results[i].name.first + ' ' + data.results[i].name.last + '</td><td>' + data.results[i].email + '</td><td>' + data.results[i].email + '</td></tr>';
}
$("#dataTable tbody").html(items);
console.log(data);
},
error: function() {
var tableRow = '<tr><td>There is no data to display</td></tr>';
console.log(tableRow);
$("#dataTable tbody").html(tableRow);
}
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<table class="table" id="dataTable">
<thead>
<tr>
<th>Full Name</th>
<th>Email</th>
<th>Address</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
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);
})
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.
I need address in project. I am getting address by using Latitude and longitude with including below scripting code.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>
Is there any respective .js file is there to find location instead of loading above URL ?
Please give some suggestions because with out internet connection my app is not loading, It is throwing Application Error.
Click here for your query. I think it will be usefull for you.
why dont you use a function() to get the location and dispaly it within the div??
chk out below:
function Location() {
var latlng = userLatValue + ',' + userLngValue;
var locationUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng="
+ latlng + "&sensor=false";
var locationRequest = $.ajax({
type : 'GET',
url : locationUrl,
async : false,
data : "json"
});
locationRequest.done(function(data) {
if(data.results.length > 0) {
userLocationName = data.results[0].formatted_address;
//alert('address: ' + userLocationName);
}
});
locationRequest.fail(function(jqXHR, textstatus, error) {
//alert("error:");});
}