leafletjs get coordinates from onLocationFound function - geolocation

I am working with leafletjs API.
I do not have experience with JS and I couldn't find any answer here.
I am trying to combine using geolocation service with leaflet routing service.
My goal is to get
latlng
value from
onLocationFound
function and passed that
information to first
waypoint
in routing service.
//INITIALIZE MAP...
var map = L.map('map');
L.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
// LOCATION SERVICE
map.locate({setView: true, maxZoom: 16});
function onLocationFound(e) {
var radius = e.accuracy / 2;
L.marker(e.latlng).addTo(map)
}
map.on('locationfound', onLocationFound);
function onLocationError(e) {
alert(e.message);
}
map.on('locationerror', onLocationError);
//End of Location service,
//GET LATLNG PARAMETERS AFTER CLICK IN CONSOLE
map.on('click', function(e)
{
tempLatitude = e.latlng.lat;
tempLongitude = e.latlng.lng;
console.log(tempLongitude);
console.log(tempLatitude);
});
// ROUTING SERVICE
var control = L.Routing.control(L.extend(window.lrmConfig, {
waypoints: [
L.latLng(57.74, 11.94),
L.latLng(57.6792, 11.949)
],
geocoder: L.Control.Geocoder.nominatim(),
routeWhileDragging: true,
reverseWaypoints: true,
showAlternatives: true,
altLineOptions: {
styles: [
{color: 'black', opacity: 0.15, weight: 9},
{color: 'white', opacity: 0.8, weight: 6},
{color: 'blue', opacity: 0.5, weight: 2}
]
}
})).addTo(map);
L.Routing.errorControl(control).addTo(map);
.

Related

HighMap data table not loading points

I'm trying to populate a map of the U.S. in HighMaps with data from an html table. The map is showing but the data point is not. It's a latitude/longitude point. The documentation is sparse, so I'm not sure what I'm doing wrong. Here's a JSFiddle: https://jsfiddle.net/sfjeld/1wjm04fc/6/
Highcharts.mapChart('container', {
chart: {
map: 'countries/us/custom/us-all-territories'
},
series: [{
name: 'Basemap',
dataLabels: {
enabled: true,
format: '{point.name}'
}
},
{
// Specify points using lat/lon
type: 'mappoint',
data: {
table: 'pvsoiling-table',
startRow: 1,
startColumn: 1,
endColumn: 2
},
name: 'PV',
marker: {
fillColor: 'white',
lineColor: 'black',
lineWidth: 2,
radius: 10
},
color: Highcharts.getOptions().colors[1]
}
]
});
thanks,
Shauna
You can make the following changes to your code:
At the start of your <script> section, load your HTML table data into a JavaScript array:
var mapData = [];
Highcharts.data({
table: document.getElementById('pvsoiling-table'),
startColumn: 1,
endColumn: 2,
firstRowAsNames: true,
complete: function (options) {
options.series[0].data.forEach(function (p) {
mapData.push({
lat: p[0],
lon: p[1]
});
});
//console.log(mapData);
}
});
We will refer to this mapData array later on. Here is what it contains:
[
{ "lat": 33.3, "lon": -111.67 }
]
Make changes to the series section in your Highcharts.mapChart.
series: [{
name: 'Basemap',
nullColor: '#e0f9e3',
dataLabels: {
enabled: true,
format: '{point.name}'
}},
{
// Specify points using lat/lon
data: mapData,
type: 'mappoint',
name: 'PV',
marker: {
fillColor: 'white',
lineColor: 'black',
lineWidth: 1,
radius: 3
},
color: Highcharts.getOptions().colors[1]
}
]
The key part to note is the data: mapData option. The JavaScript mapData variable is the exact array that we need to represent a set of points on the map. In our case the array only contains one point - but that's because there is only one relevant row of data in the HTML table.
My map ends up looking like this:
It looks like the marker is in or near Phoenix, AZ.
Final notes:
(a) I also adjusted the marker to have lineWidth: 1 and radius: 3 (a bit smaller).
(b) I added a document ready function around everything, to ensure the DataTable is loaded before you try to read its data.
(c) There may be a more elegant way to do this, but I followed the approach in this demo. The demo actually shows how to join 2 different sets of data - not what you need. But it does show a good approach for extracting the HTML data so it can be used in the map.
Using the the Highcharts.data({...}) approach lets you access any HTML table. But since you are using DataTables, you can choose to do the following, instead. It uses the DataTables API to access each row of data:
var mapData = [];
$('#pvsoiling-table').DataTable({
"initComplete": function(settings, json) {
var api = this.api();
api.rows().data().each(function (p) {
mapData.push({ lat: Number(p[1]), lon: Number(p[2]) });
});
// your Highcharts.mapChart() logic, in a function:
buildChart();
}
});

Highcharts gantt chart : Task progress indicator need to show a single task for various status like completed,inprogress etc with different colors

Refer the image
var markers = JSON.parse('<%=ConvertDataTabletoString("GetTaskWorkPercentage","2",null,1,10) %>');
var Arrayset = [];
var starts1 = [];
var ends1 = [];
var val1 = [];
var val2 = [];
if (markers != null) {
if (markers.length > 0) {
var prj = document.getElementById("param1").value;
for (var i = 0; i < markers.length; i++) {
var syearval = parseInt(markers[i].ActualStart.substr(0, 4));
var smonthval = parseInt(markers[i].ActualStart.substr(5, 2)) - 1;
var sdateval = parseInt(markers[i].ActualStart.substr(8, 2));
var eyearval = parseInt(markers[i].ActualEnd.substr(0, 4));
var emonthval = parseInt(markers[i].ActualEnd.substr(5, 2)) - 1;
var edateval = parseInt(markers[i].ActualEnd.substr(8, 2));
val1 = [Date.UTC(syearval, smonthval, sdateval)];
val2 = [Date.UTC(eyearval, emonthval, edateval)];
starts1.push(val1[0]);
ends1.push(val2[0]);
Arrayset.push({
name: markers[i].Task,
completed: markers[i].Percentages,
start: starts1[i],
end: ends1[i]
});
}
MainLoadChart(Arrayset);
}
}
function MainLoadChart(array) {
var dta = array;
Highcharts.ganttChart('container8', {
title: {
text: 'Task Progress Indicator Status'
},
tooltip: {
formatter()
{
//let output = `<span style="font-size: 10px">${this.point.series.name}</span><br>
let output = ` <span style="font-size: 20px;color:green">${prj}</span><br>
<span><b>${this.key}(Overall Subtask Percentage):${this.point.completed}% </b></span><br>
<span>Start: ${Highcharts.dateFormat('%A, %e. %b, %Y', this.x)}</span><br>
<span>End: ${Highcharts.dateFormat('%A, %e. %b, %Y', this.x2)}</span>`
return output
}
},
series: [{
data: dta,
dataLabels: {
formatter() {
//return this.point.completed;
let output1 = ` <span style="font-size: 10px">${this.point.completed}%</span>`
return output1
}
}]
});
}
Currently I´m showing the output of overall subtask. I need to show in a single task progress (overall) for various status like completed, inprogress, hold, returned with different (multiple) colors and style. So that values should not overlap or hide like datalabel values.
You should be able to achieve it by using yAxis.categories and assigning data to this one category.
Demo: https://jsfiddle.net/BlackLabel/19L48qy5/
...
yAxis: {
categories: ['Prototyping'],
},
series: [{
name: 'Project 1',
data: [{
name: 'test1',
start: Date.UTC(2014, 10, 18),
end: Date.UTC(2014, 10, 25),
y: 0
}, {
color: 'red',
name: 'test2',
start: Date.UTC(2014, 10, 18),
end: Date.UTC(2014, 10, 22),
y: 0
}, {
color: 'green',
name: 'test3',
start: Date.UTC(2014, 10, 18),
end: Date.UTC(2014, 10, 20),
y: 0
}]
}]
...
API: https://api.highcharts.com/gantt/yAxis.categories

How to display text for bubbles within Map

i'm currently testing kendo ui's map. From this example https://demos.telerik.com/aspnet-mvc/map/bubble-layer i was able to create a small example of canada and put bubbles in each province that can be found Here I was wondering how can i set a small text inside the bubbles to correspond to the json's City.
$("#map").kendoMap({
center: [56.1304, -106.3468],
minZoom: 3,
zoom: 4,
wraparound: false,
layers: [{
type: "tile",
urlTemplate: "http://#= subdomain #.tile.openstreetmap.org/#= zoom #/#= x #/#= y #.png",
subdomains: ["a", "b", "c"],
attribution: "© <a href='http://osm.org/copyright'>OpenStreetMap contributors</a>"
}, {
type: "bubble",
attribution: "Population data from Nordpil and UN Population Division.",
style: {
fill: {
color: "#00f",
opacity: 0.4
},
stroke: {
width: 0
}
},
dataSource: {
transport: {
read: {
url: "https://api.myjson.com/bins/jvcf0",
dataType: "json"
}
}
},
locationField: "Location",
valueField: "Pop2010"
}],
You can use the approach demonstrated here for shape layer:
shapeCreated: function(e) {
// Calculate shape bounding box
var bbox = e.shape.bbox();
var center = bbox.center();
// Create the label
var labelText = e.shape.dataItem.City;
var label = new kendo.drawing.Text(labelText);
var labelCenter = label.bbox().center();
// Position the label
label.position([
center.x - labelCenter.x,
center.y - labelCenter.y
]);
// Render the label on the layer surface
e.layer.surface.draw(label);
}
https://jsfiddle.net/xjyr50on/

Google Combo Charts?

I have 4 entities and I show them for 4 days. But first and last days I cant see other 2 entities.In 3 August I cant see T0,T1. In 6 August I cant see T2,T3.
Codes
var evalledData = eval("(" + result.chartData + ")");
var ac = new google.visualization.ComboChart($("#chart_div_ay").get(0));
ac.draw(new google.visualization.DataTable(evalledData, 0.5), {
//title: 'Son 7 günlük sayaç okumalarının toplamı.',
width: '100%',
height: 300,
vAxis: { title: "kW" },
hAxis: { title: "Gün" },
seriesType: "bars",
series: { 5: { type: "line"} }
});
Controller:
public ActionResult MusteriSayaclariOkumalariChartDataTable(DateTime startDate, DateTime endDate, int? musteri_id)
{
IEnumerable<TblSayacOkumalari> sayac_okumalari = entity.TblSayacOkumalari;
var sonuc = from s in sayac_okumalari
where s.TblSayaclar.musteri_id == musteri_id && s.okuma_tarihi.Value >= startDate && s.okuma_tarihi.Value <= endDate
group s by new { date = new DateTime(((DateTime)s.okuma_tarihi).Year, ((DateTime)s.okuma_tarihi).Month, ((DateTime)s.okuma_tarihi).Day) } into g
select new
{
okuma_tarihi = g.Key,
T1 = g.Sum(x => x.kullanim_T1) / 1000,
T2 = g.Sum(x => x.kullanim_T2) / 1000,
T3 = g.Sum(x => x.kullanim_T3) / 1000,
T4 = g.Sum(x => x.kullanim_T0) / 1000
};
//Get your data table from DB or other source
DataTable chartTable = new DataTable();
chartTable.Columns.Add("Tarih").DataType = System.Type.GetType("System.DateTime");
chartTable.Columns.Add("T1").DataType = System.Type.GetType("System.Double");
chartTable.Columns.Add("T2").DataType = System.Type.GetType("System.Double");
chartTable.Columns.Add("T3").DataType = System.Type.GetType("System.Double");
chartTable.Columns.Add("Toplam").DataType = System.Type.GetType("System.Double");
foreach (var item in sonuc)
{
chartTable.Rows.Add(item.okuma_tarihi.date, item.T1.Value, item.T2.Value, item.T3.Value, item.T4.Value);
}
//convert datetime value to google datetype, if your first column is date
Bortosky
.Google
.Visualization
.GoogleDataTable
.SetGoogleDateType(chartTable.Columns["Tarih"],
Bortosky.Google.Visualization.GoogleDateType.Date);
//convert DataTable to GoogleDataTable
var googleDataTable =
new Bortosky.Google.Visualization.GoogleDataTable(chartTable);
//Pass the google datatable to UI as json string
return new JsonResult
{
Data = new
{
success = true,
chartData = googleDataTable.GetJson()
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
This action return json as google examples custom data.
evalledData output:
Is there any option about this problem?
Thanks.
I recently had to build a chart like this. Please consider my code for your solution:
Put this in your Controller:
<EmployeeAuthorize()>
Function WeightAreaChartData() As JsonResult
Dim myData = db.Tbl_Weights.Where(Function(x) x.Weight_Employee_ID).OrderBy(Function(x) x.Weight_Create_Date)
Dim data = New List(Of Object)
data.Add(New Object() {"Date", "Your Weight"})
For Each i As Tbl_Weight In myData
data.Add(New Object() {DateTime.Parse(i.Weight_Create_Date).Day, i.Weight_Amount})
Next
Return Json(data, JsonRequestBehavior.AllowGet)
End Function
Put this in your view; changing the $.post() URL accordingly:
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.post('/Weight/WeightAreaChartData', {},
function (data) {
var tdata = new google.visualization.arrayToDataTable(data);
var options = {
title: 'Weight Lost & Gained This Month',
hAxis: { title: 'Day of Month', titleTextStyle: { color: '#1E4A08'} },
vAxis: { title: 'Lbs.', titleTextStyle: { color: '#1E4A08'} },
chartArea: { left: 50, top: 30, width: "75%" },
colors: ['#FF8100']
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(tdata, options);
});
}
</script>
<div id="chart_div" style="width: 580px; height: 200px;"></div>
To fix your specific issue of the bars being cut off, I believe you can use this in your options:
hAxis: {
viewWindowMode: 'pretty'
}
Like this:
var options = {
title: 'Weight Lost & Gained This Month',
hAxis: { title: 'Day of Month', titleTextStyle: { color: '#1E4A08'} },
vAxis: { title: 'Lbs.', titleTextStyle: { color: '#1E4A08' } },
chartArea: { left: 50, top: 30, width: "75%" },
colors: ['#FF8100', 'blue'],
hAxis: {
viewWindowMode: 'pretty'
}
};

Sencha Touch 2 geolocation using Google Maps

I'm trying to implement geolocation on my app written in sencha framework, but I don't really know how to implement geolocation using Sencha Touch 2 and Google Maps Api.
I have following code:
Ext.define('App.view.WhereAmI', {
extend: 'Ext.Container',
xtype: 'whereAmI',
//? fullscreen: true,
requires: [
'Ext.Map'
],
config: {
layout: 'fit',
scrollable: true,
styleHtmlContent: true,
style: 'text-align: center; background-color:white;',
items:
[
{
xtype: 'toolbar',
docked: 'top',
title: 'Where Am I?',
minHeight: '60px',
items: [
{
ui: 'back',
xtype: 'button',
id: 'backButton',
text: 'Powrót',
},
{
minHeight: '60px',
right: '5px',
html: ['<img src="resources/images/Image.png"/ style="height: 100%; ">',].join(""),
},
],
},
{
xtype:'map',
},
]
},
//launch : function () { },
});
What do I exactly need to add to this view to implement marker with my current location?
Thanks for help!
Try using geolocation :
var geo = Ext.create('Ext.util.Geolocation', {
autoUpdate:false,
listeners:{
locationupdate:function (geo) {
console.log('Current latitude: ' + geo.getLatitude() + 'Long: ' + geo.getLongitude());
},
locationerror:function (geo, bTimeout, bPermissionDenied, bLocationUnavailable, message) {
if (bTimeout) {
alert('Timeout occurred.');
} else {
alert('Error occurred.');
}
}
}
});
or add
useCurrentLocation:true,
in sencha touch map

Resources