I am having such a rough time accomplishing this and all the research I'm doing is not turning out positive. In short, I need to send an array of markers from my code to my MVC view (through the model and setting it as a hidden field) so that the Google map can use this array to place markers on the map. I have tried building it as a List and then using JSON serialization to turn it to a string, but the format just won't turn out and won't be recognizable to the Google API. Has anyone done this before successfully??
Here is my updated code based on CodeMonkey's answer, but the markers still aren't placing. I think it's happening somewhere in the addMarker function...
var lat = $("#Latitude").val();
var lng = $("#Longitude").val();
var myOptions = {};
var map = null;
var marker = null;
var global_markers = [];
var infowindow = new google.maps.InfoWindow({});
var geodata;
var markers = [];
function map_initialize() {
var myLatlng = new google.maps.LatLng(lat, lng);
myOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
#foreach (var item in Model.AllSearchResults)
{
<text>try
{
var lat = '#item.Latitude';
var lng = '#item.Longitude';
var name = '#item.Name';
var url = '#Url.Action("GetMarker", "Base")';
var model = { "Latitude": lat, "Longitude": lng, "Name": name };
$.ajax({
type: "POST",
data: model,
dataType: "json",
url: url,
success: function (data) {
geodata = data;
JSONString = JSON.stringify(geodata);
var valuesToPush = new Array();
valuesToPush[0] = data.Latitude;
valuesToPush[1] = data.Longitude;
valuesToPush[2] = data.Name;
markers.push(valuesToPush);
addMarker();
},
error: function () {
alert("fail");
}
});
}
catch (err) { }</text>
}
}
function addMarker() {
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var name = markers[i][2];
var location = new google.maps.LatLng(lat, lng);
var contentString = '<div class="infowindow"><p>' + name + '</p></div>';
var marker = new google.maps.Marker({
position: location,
map: map,
title: name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function () {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
google.maps.event.addDomListener(window, 'load', map_initialize);
I was able to do a combo server side/client side approach using the following link as a guide: http://mikehadlow.blogspot.com/2008/10/using-google-maps-with-mvc-framework.html
Thanks for Code Monkey's input!!
You can reference my front-end JS code at this URL: http://www.wallodex.com/WallodexAdmin/Map/10
This is how I use it on the VIEW:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>CloudClaims Administration - Site Visits</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDgJDbn0VP_AnX4HsXSjN3cIn0MoEJ4vOw&sensor=false"></script>
<script type="text/javascript" src="../../js/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="../../js/json2.js"></script>
<script type='text/javascript'>
var DISPLAY_COUNT = 20;
var myOptions = {};
var markerArray = new Array();
var map = null;
//var geocoder = null;
var marker = null;
var g_ctr = 0;
var last_used_address = "";
var splitURLs = {};
var global_markers = [];
var infowindow = new google.maps.InfoWindow({});
var geodata;
var markers = [];
function initialize() {
myOptions = {
center: new google.maps.LatLng(38.5111, -96.8005),
zoom: 4,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//geocoder = new google.maps.Geocoder();
#foreach (var item in Model)
{
<text>try
{
var ip = '#item';
var url = 'http://api.ipinfodb.com/v3/ip-city/?format=json&key=6d0759103a4ec817ffda18dfba4eafe853125d6960dedffdcfa4a428774d871d&ip=' + ip + '&callback=?';
$.getJSON(url,
function (data) {
if (data['statusCode'] == 'OK') {
geodata = data;
JSONString = JSON.stringify(geodata);
//callback();
//alert(data.regionName);
var valuesToPush = new Array();
valuesToPush[0] = data.latitude;
valuesToPush[1] = data.longitude;
valuesToPush[2] = data.cityName + ', ' + data.regionName;
valuesToPush[3] = data.ipAddress;
markers.push(valuesToPush);
addMarker();
}
});
}
catch (err) { }</text>
}
}
function addMarker() {
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var cityState = markers[i][2];
var ipAddress = markers[i][3];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = '<div class="infowindow"><p>' + cityState + '<br/>' + ipAddress + '</p></div>';
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Coordinates: " + lat + " , " + lng + " \n Location: " + cityState
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function () {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".fadeInbox").hide().fadeIn(4000);
$("#map_canvas").hide().fadeIn(4000);
$(".subscriberList").hide().fadeIn(8000);
});
$(window).load(function () {
$("#loading").css('visibility', 'hidden');
});
</script>
<style type="text/css">
.infowindow
{
background-color: Yellow;
text-align: left;
padding: 0px, 0px, 0px, 0px;
margin: 0px, 0px, 0px, 0px;
}
.fadeOutbox, .fadeInbox, .fadeTobox
{
padding: 10px;
margin: 4px;
border: 1px solid blue;
width: 250px;
height: 50px;
background-color: #000000;
color: white;
font: georgia;
}
.clear
{
clear: both;
}
</style>
</head>
<body onload="initialize();">
<form id="form1" runat="server">
<asp:panel id="Panel1" runat="server" style="height: 600px;">
<asp:Literal ID="js" runat="server"></asp:Literal>
<table width="100%" align="center" border="1">
<tr bgcolor="#1569C7" align="center">
<td colspan="2">
<font color="white">CloudClaims™ - Site visitors - Last X days</font>
</td>
</tr>
<tr align="center">
<td width="80%">
<div id="map_canvas" style="width: 100%; height: 620px; margin-bottom: 0.5px;"></div>
</td>
<td align="center" valign="bottom" bgcolor="#FFBD82">
<asp:Label runat="server" id="errors"/>
<div>
#{Html.RenderAction("Subscribers");}
</div>
<div align="center" class="fadeInbox">
<b>DEBUGGING</b><br />
<asp:Label runat="server" id="ajaxtest"/>
</div>
</td>
</tr>
</table>
</asp:panel>
</form>
</body>
</html>
And this is my CONTROLLER (I convert IP ADDRESSES to gMap objects on the front-end but you get the idea...):
public ActionResult Map(int id)
{
try
{
using (var db = new CloudClaimsEntities())
{
DateTime dateFrom = (id != null && id > 1) ? DateTime.Now.AddDays(-id) : DateTime.Now.AddDays(-1);
List<string> IPAddresses = new List<string>();
IPAddresses = db.IPLogs
.Where(i => i.timeStamp <= DateTime.Now)
.Where(i => i.timeStamp >= dateFrom)
.Select(i => i.IPAddress)
.ToList();
return View(IPAddresses);
}
}
catch
{
return View();
}
}
Related
I want to save my coordinates from the frontend to the backend and I don't know how to send them.
the coordinates are saved in a JS array and I don't know how to transfer them to C#.
HTML, CSS & JS for the map
<link rel="stylesheet" href="~/css/ol.css">
<link rel="stylesheet" href="~/css/ol-ext.css">
<script src="~/js/ol.js"></script>
<script src="~/js/ol-ext.js"></script>
#*<script src="~/js/elm-pep"></script>*#
#*<script src="~/js/JavaScript.js"></script>*#
<div id="map" style="width:600px; height:400px;">
<div class="photon ol-search ol-unselectable ol-control ol-collapsed">
<input asp-for="coordinates" type="search" class="search" autocomplete="off" placeholder="Search...">
<input asp-for="coordinates" type="button" class="ol-revers" title="click on the map">
<ul class="autocomplete history">
<li data-search="0"> 398<i> 9350004 Jérusalem (Israël)</i></li>
<li class="copy">© OpenStreetMap contributors</li>
</ul>
</div>
</div>
<div class="button-70" style="z-index:1;" id="location-button">
#*<button id="location-button" title="Get your location"></button>*#
#*<button asp-for="coordinates" class="button-70" id="location-button" role="button" title="Get your current location">📍 Get cuttent location</button>*#
<input asp-for="coordinates" type="button" value="📍 Get cuttent location" id="location-button" />
</div>
<style>
.button-70 #location-button {
background: none;
border: none;
transform: scale(2)
}
.button-70 {
transform: scale(0.7);
background-image: linear-gradient(#0dccea, #0d70ea);
border: 0;
border-radius: 4px;
box-shadow: rgba(0, 0, 0, .3) 0 5px 15px;
box-sizing: border-box;
color: #fff;
cursor: pointer;
font-family: Montserrat,sans-serif;
font-size: .9em;
margin: 5px;
padding: 10px 15px;
text-align: center;
user-select: none;
-webkit-user-select: none;
touch-action: manipulation;
}
</style>
<script type="text/javascript">
var layers = [new ol.layer.Tile({ source: new ol.source.OSM() })];
var map = new ol.Map({
target: 'map',
view: new ol.View({
zoom: 5,
center: [166326, 5992663]
}),
interactions: ol.interaction.defaults({ altShiftDragRotate: false, pinchRotate: false }),
layers: layers
});
var search = new ol.control.SearchPhoton({
lang: "fr",
reverse: true,
position: true
});
map.addControl(search);
var markers;
search.on('select', function (e) {
map.getView().animate({
center: e.coordinate,
zoom: Math.max(map.getView().getZoom(), 16)
});
loc(e.coordinate);
});
function loc(e) {
console.log(e);
if (markers) {
map.removeLayer(markers)
}
markers = new ol.layer.Vector({
source: new ol.source.Vector(),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'https://ucarecdn.com/4b516de9-d43d-4b75-9f0f-ab0916bd85eb/marker.png' // => https://app.uploadcare.com/projects/c05bbeb5e1a61e862903/files/7110cd57-b0ee-4833-bcd1-ff0343dd01cc/?limit=100&ordering=-datetime_uploaded
})
})
});
map.addLayer(markers);
var marker = new ol.Feature(new ol.geom.Point(e));
markers.getSource().addFeature(marker);
}
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
document.querySelector("#location-button").addEventListener("click", function (e) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
console.log(e);
if (markers) {
map.removeLayer(markers)
}
markers = new ol.layer.Vector({
source: new ol.source.Vector(),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'https://ucarecdn.com/4b516de9-d43d-4b75-9f0f-ab0916bd85eb/marker.png' // => https://app.uploadcare.com/projects/c05bbeb5e1a61e862903/files/7110cd57-b0ee-4833-bcd1-ff0343dd01cc/?limit=100&ordering=-datetime_uploaded
})
})
});
map.addLayer(markers);
function success(pos) {
const crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
return new Array(crd.latitude, crd.longitude);
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);
var marker = new ol.Feature(new ol.geom.Point(ol.proj.fromLonLat([position.coords.latitude, position.coords.longitude])));
markers.getSource().addFeature(marker);
});
}
else {
alert("Your browser does not support geolocation");
}
});
</script>
I tried to save the coordinates in A list and in a string, but none worked.
here is the Model code:
public class ReportModel
{
//...stuff...
public string coordinates { get; set; }
//...more stuff...
}
ReportDAO.cs - Saves the given data form the user
using Microsoft.Data.SqlClient;
using SvivaTeamVersion3.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SvivaTeamVersion3.Services
{
public class ReportDAO
{
static readonly string connectionString = #"KEY";
public static bool addReport(ReportModel report)
{
bool success = false;
string sqlStatement = "INSERT INTO dbo.Reports (category,title,description,statUrgence,cordsLat,cordsLong) VALUES (#category,#title,#description,#statUrgence,#cordsLat,#cordsLong)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sqlStatement, connection);
command.Parameters.Add("#category", System.Data.SqlDbType.NChar, 32).Value = report.category;
command.Parameters.Add("#title", System.Data.SqlDbType.NChar, 32).Value = report.title;
command.Parameters.Add("#description", System.Data.SqlDbType.NVarChar, -1).Value = report.remarks;
command.Parameters.Add("#statUrgence", System.Data.SqlDbType.NVarChar, -1).Value = report.statUrgence;
command.Parameters.Add("#cordsLat", System.Data.SqlDbType.Float).Value = report.coordinates;
command.Parameters.Add("#cordsLong", System.Data.SqlDbType.Float).Value = 0;
//I've tried to merge the lat and long to a single string, didn't work.
try
{
connection.Open();
command.ExecuteNonQuery();
success = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return success;
}
}
}
}
Webchat version: 4.15.1 using CDN,
Description: I am using HeroCards with postback buttons but they show the text in the value after I click them, It also happens with SuggestedActions. Since in some cases I am using special codes I need to hide them from the user
Code of the cards:
private async Task<DialogTurnResult> ProcesarEnvioMenu(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
var tarjetaNecesitoPrueba = new HeroCard()
{
Buttons = new List<CardAction>()
{
new CardAction()
{
Title = "Pruebas",
Type = ActionTypes.PostBack,
Value = "Pruebas"
}
},
Images = new List<CardImage>()
{
new CardImage()
{
Url="https://chatbotfcsblobstorage2.blob.core.windows.net/imagenes/63de5d7e-bf00-498f-bb1a-84c16feef299.png"
}
},
Title = "Necesito una prueba diagnóstica ",
Subtitle = "para saber si tengo COVID"
}.ToAttachment();
var mensaje = stepContext.Context.Activity.CreateReply($"Por favor elige la opción que deseas o si lo prefieres hazme una pregunta directamente.");
mensaje.Attachments = new List<Attachment>();
mensaje.AttachmentLayout = AttachmentLayoutTypes.Carousel;
mensaje.Attachments.Add(tarjetaNecesitoPrueba);
await stepContext.Context.SendActivityAsync(mensaje, cancellationToken: cancellationToken);
return await stepContext.EndDialogAsync();
}
Code of the webchat:
<!DOCTYPE html> <html> <head>
<script src="https://cdn.botframework.com/botframework-webchat/4.15.1/webchat.js"></script>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
}
#webchat {
height: 100%;
width: 100%;
}
</style> </head> <body>
<div id="webchat" role="main"></div>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
const styleSet = window.WebChat.createStyleSet({
rootHeight: '100%',
rootWidth: '100%',
bubbleFromUserBackground: '#EA431C',
bubbleFromUserBorderRadius: 15,
bubbleFromUserBorderColor: '#EA431C',
bubbleFromUserTextColor: 'White',
bubbleBackground: '#24B5B1',
bubbleBorderRadius: 15,
bubbleBorderColor: '#24B5B1',
bubbleTextColor: 'White',
sendBoxButtonColor: '#0063B1',
sendBoxBorderBottom: 'solid 1px #006FBA',
sendBoxBorderLeft: 'solid 1px #006FBA',
sendBoxBorderRight: 'solid 1px #006FBA',
sendBoxBorderTop: 'solid 1px #006FBA',
suggestedActionBackgroundColor: '#EA431C',
suggestedActionBorderColor: '#EA431C',
suggestedActionBorderColor: 'White',
suggestedActionTextColor: 'White',
suggestedActionBorderStyle: 'none',
suggestedActionBorderRadius: 5,
});
styleSet.textContent = {
...styleSet.textContent,
fontFamily: "'Gotham', 'Calibri', 'Helvetica Neue', 'Arial', 'sans-serif'",
fontColor: 'White'
};
const avatarOptions = {
botAvatarBackgroundColor: '#FE9913',
botAvatarImage: 'https://wikiaprendofcscontainer.blob.core.windows.net/imagenes/wikiaprendo/logowikiaprendofcs.png',
botAvatarInitials: 'BF',
hideUploadButton: true,
};
(async function () {
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join'
}
});
}
return next(action); });
const token = '#ViewBag.Token';
var d1 = window.WebChat.createDirectLine({ token })
window.WebChat.renderWebChat({
directLine: Object.assign({}, d1, {
postActivity: activity => {
var newActivity = Object.assign({}, activity, { channelData: { "MonitorId": "#ViewBag.IdMonitor" } });
return d1.postActivity(newActivity);
}
}),
styleSet,
styleOptions:avatarOptions,
store,
sendTypingIndicator:true
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script> </body> </html>
The error was in the webchat configuration on the html file. This is the right way of having a welcome message AND passing arguments to a chatbot in the channel data
(async function () {
const token = '#ViewBag.Token';
var d1 = window.WebChat.createDirectLine({ token });
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join',
value: { language: window.navigator.language }
}
});
}
if (action.type === 'DIRECT_LINE/POST_ACTIVITY') {
action = window.simpleUpdateIn(
action,
['payload', 'activity', 'channelData', 'MonitorId'],
() => '#ViewBag.IdMonitor'
);
}
return next(action);
});
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({ token }),
store,
styleSet,
styleOptions: avatarOptions
},
document.getElementById('webchat')
);
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
I have a .Net Core application and in one of my views I want to have a Google Map in which I want to be able to draw dynamical polylines.
Index.cshtml
I have included a Google Map on my view as follows:
<div class="col-md-6 col-lg-6">
<h3>My Google Maps Demo</h3>
<div id="map"></div>
</div>
<script>
function initMap() {
var center = { lat: 55.92965249, lng: 12.47840507 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: uluru
});
$.get()
$.post()
route.setMap(map);
}
</script>
And in my _Layout.cshtml I have:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=...api key...&callback=initMap">
</script>
All of this works as intended, but I am unsure of whether this is the proper way to show Google Maps in a .Net Core application?
Furthermore I want to be able to draw dynamical routes in my Google Maps implementation. This is done via the following code
var route = new google.maps.Polyline({
path: routeCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
where routeCoordinates is a list of coordinates:
var routeCoordinates = [
{lat: 55.92965249, lng: 12.47840507},
{lat: 55.92941392, lng: 12.47832253},
{lat: 55.92918626, lng: 12.47824027},
...
{lat: 55.91474539, lng: 12.47145191},
{lat: 55.91450191, lng: 12.47139283},
{lat: 55.91425197, lng: 12.47134614}
]
All the above is of course done statically in my Index.cshtml.
So is there a better way to do this? And how would I go about adding and removing lines dynamically (hopefully) by using my Controller? I expect something like:
public async Task<IActionResult> Index()
{
return View(await _context.Trips.ToListAsync());
//context is my db
}
Right now it is not present but I will be getting a list of coordinates from my context through my EF implementation.
EDIT:
Since I posted this I have continued a bit, and I now have a PartialView that I want to load when clicking a table row:
MapPartialView.cshtml
#model IEnumerable<LngLat>
<div class="col-md-6 col-lg-6">
<h3>My Google Maps Demo</h3>
<div id="map"></div>
</div>
<script>
function initMap() {
var center = { lat: 55.92965249, lng: 12.47840507 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: center
});
//$.get();
//$.post();
routeCoordinates = #Model;
var route = new google.maps.Polyline({
path: routeCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
route.setMap(map);
}
</script>
And my:
Index.cshtml
// table header and so forth..
<tbody>
#foreach (var item in Model)
{
<tr class="trips" data-id="#item.TripID" data-url="#Url.Action("ExpandMap", "Trip")">
<td>
#Html.DisplayFor(modelItem => item.DeviceID)
</td>
<td>
#Html.DisplayFor(modelItem => item.StartTime)
</td>
<td>
#Html.DisplayFor(modelItem => item.Duration)
</td>
<td>
#Html.DisplayFor(modelItem => item.StartLocation)
</td>
<td>
#Html.DisplayFor(modelItem => item.EndLocation)
</td>
</tr>
}
</tbody>
<div id="partialMap"></div>
And in my:
site.js
$('.trips').each(function (i, e) {
var _this = $(this);
var element = $(e).children('td');
element.click(function () {
//console.log("Clicked! " + _this.data('url') + " " + _this.data('id'));
$("#partialMap").load(_this.data('url'), { id: _this.data('id') }, function () {
$("#partialMap").slideDown('200');
});
});
});
And lastly my controller and the ExpandMap function:
TripController.cs
public IActionResult ExpandMap(int id)
{
var trip = _context.Trips.SingleOrDefault(t => t.TripID == id);
List<LngLat> routeCoordinates = new List<LngLat>
{
new LngLat() { lat = 55.92965249, lng = 12.47840507},
new LngLat() { lat = 55.92941392, lng = 12.47832253},
...
new LngLat() { lat = 55.91450191, lng = 12.47139283},
new LngLat() { lat = 55.91425197, lng = 12.47134614}
};
string routeCoordinatesJS = JsonConvert.SerializeObject(routeCoordinates, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
return PartialView("MapPartialView", routeCoordinatesJS);
}
But when I run the code I get a:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
You can export your context to a list of lat and lng
public class LngLat
{
public double lat { get; set; }
public double lng { get; set; }
}
The build your list with data from your db and send it to the View():
public async Task<IActionResult> Index()
{
List<LngLat> routeCoordinates = await _context.Trips.Select(c=> new LngLat {lat = c.latitude, lng = c.longitude })
//Serialize your routeCoordiamte with Json.Net
string routeCoordinatesJs = JsonConvert.SerializeObject(routeCoordinates, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })
return View(routeCoordinatesJs);
}
In your View():
var routeCoordinates = #Model
My script produces data but jQuery DataTables doesn't load it and shows the following error:
DataTables warning: table id=example - Requested unknown parameter 'FTR_Kno' for row 0
Should I use mvc-datatables?
View:
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="~/Content/DataTables/css/dataTables.jqueryui.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<div>
<input id="Button1" type="button" value="button" />
</div>
<div>
<form>
<table id="example">
<thead>
<tr>
<td>FTR_Kno</td>
<td>FTR_KodBelge</td>
<td>FTR_TarihBelge</td>
<td>TDR_KodTedarikci</td>
<td>KRM_AckAd</td>
<td>FTR_Ack</td>
<td>FTS_Ack</td>
</tr>
</thead>
<tbody>
#*<tr>
<td>a</td>
<td>a</td>
<td>a</td>
<td>a</td>
<td>a</td>
<td>a</td>
</tr>*#
</tbody>
</table>
</form>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function () {
$("#Button1").click(function () {
alert("bas");
$.ajax({
url: '/DataTables/jsonIndex',
type: "POST",
dataType: "json",
success: function (gdata) {
alert(gdata);
$('#example').DataTable({
data: gdata,
paging: false,
columns: [
{ "data": "FTR_Kno" },
{ "data": "FTR_KodBelge" },
{ "data": "FTR_TarihBelge" },
{ "data": "TDR_KodTedarikci" },
{ "data": "KRM_AckAd" },
{ "data": "FTR_Ack" },
{ "data": "FTS_Ack" }
]
});
}
});
});
});
</script>
> Controlller :
[HttpPost]
public JsonResult jsonIndex()
{
CultureInfo c = Thread.CurrentThread.CurrentCulture;
string userLanguage = c.TwoLetterISOLanguageName;
Session["language"] = userLanguage;
string language = Session["language"].ToString();
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
ServiceReference1.Grid grid = new ServiceReference1.Grid();
grid = client.GetGridInformation("TUR", "lst_afhFTR");
List<ServiceReference1.Column> column = new List<ServiceReference1.Column>();
column.AddRange(grid.columnList);
//Dim columnName As List(Of String) = grid.columnList.Select(Function(f) f.columnName).ToList()
ViewBag.ColumnList = grid.columnList;
ViewBag.GridWidth = grid.gridWidth;
ViewBag.GridHeader = grid.gridHeader;
client.Close();
ServiceReference1.Service1Client client1 = new ServiceReference1.Service1Client();
grid.gridCode = grid.gridCode.Insert(6, " top " + grid.gridMaxRecord.ToString());
string[] array = grid.gridCode.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
string code = "";
foreach (string item in array)
{
code = code + " " + item;
}
grid.gridCode = code;
List<Dictionary<string, object>> result = new List<Dictionary<string, object>>();
result.AddRange(client1.GetTable(grid.gridCode));
////WebGrid içine gönderilecek data oluşturulması
//IList<object> asildata = new List<object>();
//dynamic data = new List<ExpandoObject>();
//foreach (var Pairs in result)
//{
// var row = new ExpandoObject();
// List<object> row2 = new List<object>();
// foreach (var Pair in Pairs)
// {
// ((IDictionary<string, object>)row).Add(Pair.Key, Pair.Value);
// row2.Add(Pair.Value);
// }
// data.Add(row);
// asildata.Add(row2);
//};
JavaScriptSerializer js = new JavaScriptSerializer();
return Json(js.Serialize(result),JsonRequestBehavior.AllowGet);
}
}
You're encoding into JSON twice, first with Serialize() and then with Json().
Replace:
JavaScriptSerializer js = new JavaScriptSerializer();
return Json(js.Serialize(result),JsonRequestBehavior.AllowGet);
with:
return Json(result, JsonRequestBehavior.AllowGet);
I am using a map control from telerik, with shome markers:
#(Html.Kendo().Map()
.Name("map")
.Layers(layers =>
{
layers.Add()
.Type(MapLayerType.Tile)
.UrlTemplate("http://tile.openstreetmap.org/#= zoom #/#= x #/#= y #.png")
.Subdomains("a", "b", "c")
.Attribution("© <a href='http://osm.org/copyright'>OpenStreetMap contributors</a>." +
"Tiles courtesy of <a href='http://www.opencyclemap.org/'>Andy Allan</a>");
layers.Add()
.Type(MapLayerType.Marker)
.DataSource(dataSource => dataSource.GeoJson()
.Read(read => read.Action("GetMarkers", "MyController"))
)
.Tooltip(t => t.ContentHandler("GetTooltipContent"))
.LocationField("LatLng")
.TitleField("Title");
}).Events(e => e.MarkerClick("MarkerClicked")))
I need that all markers fit in the initial map view, with the correct zoom and center location.
I have used the gmaps javascript plugin for google maps and I know there are functions fitZoom()/fitBounds() to achieve this
Is there any way to achieve this with Kendo controls?
Using jQuery you can set bound for map.
function createMap() {
var markers = [
{"latlng":[34.2675,38.7409], "name": "One"},
{"latlng": [30.2707,-97.7490],"name": "Two"},
{"latlng": [30.2705,-90.4444],"name": "Three"},
{"latlng": [31.8520,33.8911], "name": "Four"}];
$("#map").kendoMap({
layers: [{
type: "tile",
urlTemplate: "http://tile.openstreetmap.org/#= zoom #/#= x #/#= y #.png",
subdomains: ["a", "b", "c"],
attribution: "© <a href='http://osm.org/copyright'>OpenStreetMap contributors</a>." +
"Tiles courtesy of <a href='http://www.opencyclemap.org/'>Andy Allan</a>"
}, {
type: "marker",
dataSource: {
data: markers
},
locationField: "latlng",
titleField: "name"
}]
});
var map = $("#map").getKendoMap();
var layer = map.layers[1];
var markers = layer.items;
var extent;
for (var i = 0; i < markers.length; i++) {
var loc = markers[i].location();
if (!extent) {
extent = new kendo.dataviz.map.Extent(loc, loc);
} else {
extent.include(loc);
}
}
map.extent(extent);
}
$(document).ready(createMap);
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/map/index">
<style>html { font-size: 12px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.material.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.dataviz.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.318/styles/kendo.dataviz.material.min.css" />
<script src="http://cdn.kendostatic.com/2015.1.318/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.318/js/kendo.all.min.js"></script>
</head>
<body>
<div id="example">
<div class="demo-section k-header" style="padding: 1em;">
<div id="map"></div>
</div>
</div>
</body>
</html>
I did that with an ajax call in an asp.net mvc5 application
the controller
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult GetMarkers( )
{
var listMarkers = new List<Markers>() { new Markers() { Latitude=34.2675, Longitude= 38.7409, Name="Pos1"},
new Markers() { Latitude=30.2707, Longitude=-97.7490, Name="Pos2"},
new Markers() { Latitude=30.2705, Longitude=-90.4444, Name="Pos3"},
new Markers() { Latitude=31.8520, Longitude=33.8911, Name="Pos4"},
new Markers() { Latitude=33.8520, Longitude=32.8911, Name="Pos5"},
new Markers() { Latitude=60.2707, Longitude=-97.7490, Name="Pos6"},
new Markers() { Latitude=20.2705, Longitude=-90.4444, Name="Pos7"},
new Markers() { Latitude=50.8520, Longitude=33.8911, Name="Pos8"},
new Markers() { Latitude=40.8520, Longitude=32.8911, Name="Pos9"}};
var json = JsonConvert.SerializeObject(listMarkers);
return Json(json, JsonRequestBehavior.AllowGet);
}
}
The Model:
public class Markers
{
public string Name { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public double[] LatLong { get { return new double[] { Latitude , Longitude}; } }
}
and the view
<ul id="panelbar">
<li class="k-state-active">
<span class="k-link k-state-selected">Getting Started</span>
<div id="map" style="width: 960px; height: 600px"></div>
</li>
<li>
</li>
</ul>
<script>
$(function () {
var markers;
$.ajax({
url: "../Home/GetMarkers",
dataType: 'json',
async: false,
success: function (data) {
markers = data;
}
});
$("#panelbar").kendoPanelBar();
$("#map").kendoMap({
layers: [{
type: "tile",
urlTemplate: "http://a.tile.openstreetmap.org/#= zoom #/#= x #/#= y #.png",
attribution: "© <a href='http://osm.org/copyright'>OpenStreetMap contributors</a>."
}, {
type: "marker",
dataSource: {
data: JSON.parse(markers)
},
locationField: "LatLong",
titleField: "Name"
}]
});
});
</script>