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?
Related
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 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 trying to find method to merge many polygon ( >100 ) in order to have only 1 polygon to have just the border of the merged polygon, not border for all "little" polygon
I import coordinates from JSON file and I use this code to render each polygon:
var thisUcVar<?php echo $nb_fichier ?>;
var thisAgencyVar<?php echo $nb_fichier ?>;
var thisListAgencyVar;
var thisUcColor;
$.getJSON("<?php echo("test/". $fichier); ?>", function(json1) {
var i=0;
var coordUc = [];
var thisUc = json1;
thisUcVar<?php echo $nb_fichier ?> = thisUc[0].name;
thisAgencyVar<?php echo $nb_fichier ?> = thisUc[0].agency;
thisUcColor = thisUc[0].color;
$.each(json1, function(key, data){
i = 0;
$.each(data.coordinates, function(key, data){
coordUc.length = 0;
$.each(data, function(key, data){
var innerCoordUc = {"lat": data[1], "lng": data[0] };
coordUc[i] = innerCoordUc;
i++;
});
var uc = new google.maps.Polygon({
title: i,
strokeWeight: 1,
fillColor: thisUcColor,
paths: coordUc,
zIndex: 10
});
uc.setMap(map);
map.addListener('zoom_changed',function(){
if(map.getZoom()>=10){
uc.set('zIndex', 90);
}else{
uc.set('zIndex', 10);
}
});
uc.addListener('click', function() {
$(".layer").html("<h1>" + thisUcVar<?php echo $nb_fichier ?> + "</h1><ul></ul>");
$.each(thisAgencyVar<?php echo $nb_fichier ?>, function(key, data){
listThisAgencyVar = data.name;
$(".layer").append("<li>" + uc.title + listThisAgencyVar + "</li>");
});
if(map.getZoom() >= 10){
map.setZoom(11);
map.setCenter(uc.getBounds().getCenter());
}
});
if (!google.maps.Polygon.prototype.getBounds) {
google.maps.Polygon.prototype.getBounds=function(){
var bounds = new google.maps.LatLngBounds()
this.getPath().forEach(function(element,index){bounds.extend(element)})
return bounds;
}
}
});
});//fin de boucle json1
});
Result is like image below:
And here one of the JSON files that I'm using to generate each polygons.
JSON used to generate polygons group
I search everywhere and I didn't find any way to merge many polygons in one big ...
Thanks a lot
A solution that might work is using the Turf library. In particular, it has a union method that does exactly what you want (merge multiple polygons into one that corresponds to the union of the polygons).
However, this library uses the Geojson standard format so you will need to convert your data into this standard.
If you can use this format, it will also help you to display the data on the map using a DataLayer and the loadGeoJson method from Google Maps API.
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).
I am trying to add markers to my Google map dynamically using a combination of ajax and php.
The first part of the code sends the latlng to the php file. The php file then returns the marker location needed.
When I alert the return part (ALERT TEST TO ENSURE PHP PROCESSED DATA CORRECTLY), it looks OK, but I cant seem to add the markers from the return on to my map.
See code below.
//SEND DATA TO URL (send to php file)
//RETURN DATA FOR PLACE MARKERS (this is what the return php file produces)
Many thanks,
//SEND DATA TO URL
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}}
xmlHttp.open("POST",'MYPHPFILE',true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("LATLON="+strLAT);
//RETURN DATA FOR PLACE MARKERS
var wxlatlng = new google.maps.LatLng(52,1);
var marker = new google.maps.Marker({
position: wxlatlng,
map: map,
icon: '../../icons/flags/traffic_light_red.png',
title: 'TEST', });
//RETURN DATA FOR PLACE MARKERS
var wxlatlng = new google.maps.LatLng(52,1.1);
var marker = new google.maps.Marker({
position: wxlatlng,
map: map,
icon: '../../icons/flags/traffic_light_red.png',
title: 'TEST', });
//ALERT TEST TO ENSURE PHP PROCESSED DATA CORRECTLY
function HandleResponse(response) {
document.getElementById('ResponseDiv').innerHTML = response;
alert($('#ResponseDiv').text());
}
The answer i found for my question was to use the php file to create the markers xml file and load the xml file via jQuery response
See code below;
jQuery.get(YOURXMLFILE, function(data) {
jQuery(data).find("marker").each(function() {
var eachMarker = jQuery(this);
var markerCoords = new google.maps.LatLng(
parseFloat(eachMarker.find("Lat").text()),
parseFloat(eachMarker.find("Lng").text())
);
var header = eachMarker.find("title").text();
var content = eachMarker.find("Content").text();
var wxicon = eachMarker.find("icon").text();
//--------------------------------------------------------------------------
marker = new google.maps.Marker({
position: markerCoords,
icon: wxicon,
map: map,
animation: google.maps.Animation.DROP,
title: header,
});
});
});