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>
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 pass php $var into Javascript from controller. $var has fetched addresses from DB. And i put it in Javascript. Now i can see the addresses in the console. No problem with that, I don't know why syntax error pop up too.
This is how I insert it into JS.
function initMap(){
var options = {
zoom:8,
center:
'{!! $estates[0]->address !!}'
}
var map = new google.maps.Map(document.getElementById("map"), options);
var marker = new google.maps.Marker({
position:
#foreach($estates as $addr)
'{!! $addr->address !!}',
#endforeach
map:map
});
var infoWindow = new google.maps.InfoWindow({
content:'content here'
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
});
}
my foreach running without a problem I can see the addreses in the console but also at this line: '{!! $estates[0]->address !!}' error pops up too. Actually I am seeing the address not this line.
error is this:
Uncaught SyntaxError: Invalid or unexpected token
Do you have any idea? am I making syntax mistake. But if do that then how can I retrieving the addresses at the console?
Also having this error too at the same line:
Undefined variable: estates (View:
/var/www/html/laravel/resources/views/layouts/app.blade.php) (View:
/var/www/html/laravel/resources/views/layouts/app.blade.php)
Controller
public function index()
{
$estates = DB::table("allestates")
->get();
return view("home", compact('estates'));
}
the topic is different the duplicated ones. it's not pure JS i am working with Laravel.
I think one of the addresses contains the ' character. To avoid it use the addslashes function. You could do that in the controller:
public function index()
{
$estates = DB::table("allestates")->get()->map(function($estate) {
$estate->address = addslashes($estate->address);
return $estate;
});
return view("home", compact('estates'));
}
And the according js would be:
var options = {
zoom:8,
center: new google.maps.LatLng({{$estates[0]->lat}}, {{$estates[0]->long}});
}
Because you have multiple addresses, it means you will have multiple markers too. That being said your code should look something like:
function initMap(){
var options = {
zoom:8,
center: new google.maps.LatLng({{$estates[0]->lat}}, {{$estates[0]->long}});
}
var map = new google.maps.Map(document.getElementById("map"), options);
var infoWindow = new google.maps.InfoWindow({
content:'content here'
});
var markers = [];
#foreach ($estates as $key => $estate)
markers[{{$key}}] = new google.maps.Marker({
position: new google.maps.LatLng({{$estate->lat}}, {{$estate->long}});
map: map
});
markers[{{$key}}].addListener('click', function () {
infoWindow.open(map, markers[{{$key}}]);
});
#endforeach
}
You can use php variables inside laravel blade files as
var options = {
zoom:8,
center:
'{{$estates[0]->address}}'
}
I'm having an issue accessing a json file from a js script in a Laravel project.
I am using the Google maps API to add markers to a map, which are all currently hard-coded because I can only seem to access the json from within a listener function.
I am fully able to access my json through the placeMarker click listener, but when i try to make the "otherPlace" using json values, the values cannot be found. Not sure what's going on here.
Sorry for the likely noob question but I am stumped and couldn't find any similar questions.
Map script Example:
function myMap() {
var mapProp= {
center:new google.maps.LatLng(44.5458062,-83.54936229999996),
zoom:8,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var place = new google.maps.LatLng(44.453,-83.45773609999998);
var placeMarker = new google.maps.Marker({position: place});
var otherPlace = new google.maps.LatLng(json.locations[4].lat,json.locations[4].lng);
var otherPlaceMarker = new google.maps.Marker({position: otherPlace});
placeMarker.setMap(map);
otherPlaceMarker.setMap(map);
placeMarker.addListener('click', function() {
map.setZoom(13);
map.setCenter(placeMarker.getPosition());
console.log(json.locations[5].address);
var infowindow = new google.maps.InfoWindow({
//content: json.locations[5].name + "\r\nAddress: " + json.locations[5].address
});
infowindow.setContent(
"<p>" + json.locations[5].name + "<br />" + json.locations[5].address + "<br/> <a href='#'>Get Directions</a> </p>"
);
infowindow.open(map,placeMarker);
});
}
In my controller I grab the json file and pass it to the view
public function locations() {
$path = storage_path() . "/json/locations.json";
$json = json_decode(file_get_contents($path), true);
return view('home/locations', compact('json'));
}
In my locations.blade.php I add the map script and pass the json to javascript
#section('scripts')
<script src="/js/locationsMap.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key={{ env('APP_GOOGLE_MAPS') }}&callback=myMap"></script>
<script>
var json = {!! json_encode($json) !!};
</script>
#endsection
Try removing var from var json if that doesn't work, put your function below json = {!! json_encode($json) !!}; and try then
I have some js code, that I would like to move to an external js file, but the script references razor syntax (url path) in the View.
Here is the script:
function getStops() {
var url = $('#map').data('request-url');
$.getJSON(url,
function (data) {
var marker = [];
$.each(data,
function (i, item) {
marker.push({
'location': new google.maps.LatLng(item.Latitude2, item.Longitude2),
'map': map,
'weight': item.Difference,
'radius': 10
});
});
var pointArray = new google.maps.MVCArray(marker);
heatmap = new google.maps.visualization.HeatmapLayer({
data: pointArray
});
heatmap.setMap(map);
});
};
// get Driving and show on layer
function getDriving() {
var url = $('#map').data('request-url2');
$.getJSON(url,
function (data) {
var marker = [];
$.each(data,
function (i, item) {
marker.push({
'location': new google.maps.LatLng(item.Latitude2, item.Longitude2),
'map': map,
'weight': item.Speed,
'radius': 10
});
});
var pointArray = new google.maps.MVCArray(marker);
heatmap = new google.maps.visualization.HeatmapLayer({
data: pointArray
});
heatmap.setMap(map);
});
I know about data-request-url that I can reference in an element (in my case it's a div).
So I wrote it like this in the View:
<div id="map" data-request-url="#Url.Action("GetStops", "Home")" data-request-url2="#Url.Action("Driving", "Home")">
Is this the right way to go, or can it be done in other way?
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).