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>
Related
This is my ViewComponet:
#model X.PagedList.PagedList<CbWebApp.DTOs.UsuarioDTO>
#using X.PagedList.Mvc.Core
#using X.PagedList.Mvc.Common
//.....more code
<div class="pagination-sm text-center">
Página #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) de
#Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("ListaUsuario", new { page = page }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions { Display = PagedListDisplayMode.IfNeeded, MaximumPageNumbersToDisplay = 5 }, new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "Get", UpdateTargetId = "usuariosPartial" }))
</div>
// more code....
My partialView that has the ViewComponent to be rendered and the DIV of reference:
<div id="usuariosPartial" class="col-xs-12 col-md-12">
#await Component.InvokeAsync("Usuario")
</div>
Maybe I can get the X.PagedList HTML id for JQuery for instance something like that:
// is this the correct id?
$("#pagesizelist").change(function (event) {
I tried that id but with no success. :(
Well, I found this solution but I am not sure if is the best approach:
JQuery - Give an ID to your table tr tag and reference it on the click event of an 'a' tag in jQuery as follows:
$('#replaceMyTr').on('click', 'a', function (e) {
e.preventDefault();
$("#icon").hide();
$("#progress").show();
$("#msg").hide();
$('input, button, a').disable(true);
var IdDoPerfilDoUsuario;
var este = $(this);
function getUrlVars() {
var vars = [], hash;
var hashes = este.attr("href").slice(este.attr("href").indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var page = getUrlVars()["page"];
if ($("select option:selected").first().val() === "--Todos--") {
IdDoPerfilDoUsuario = 0;
}
else {
IdDoPerfilDoUsuario = $("select option:selected").first().val();
}
$("#usuariosPartial").hide();
este.attr('disabled', 'disabled');
$.ajax({
url: "/Usuario/ListaUsuario",
type: 'GET',
cache: false,
data: { IdDoPerfilDoUsuario: IdDoPerfilDoUsuario, page: page },
success: function (result) {
$("#icon").show();
$("#progress").hide();
$("#msg").show();
$('input, button, a').disable(false);
$("#usuariosPartial").show();
$('#usuariosPartial').html(result);
}
});
return false;
});
View code:
// more code...
<tfoot>
<tr id="replaceMyTr">
#*<td colspan="7">*#
<td>
<div class="pagination-sm text-center">
#Html.PagedListPager((IPagedList)Model.Usuarios.ToEnumerable(), page => Url.Action("ListaUsuario", new { page = page }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions { Display = PagedListDisplayMode.IfNeeded, MaximumPageNumbersToDisplay = 5 }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "teste" }))
</div>
</td>
</tr>
</tfoot>
//....more code
I need to save canvas image by using ajax or javascript...!!
tks!
my view
#using (Html.BeginForm("SaveImage", "Campaign", FormMethod.Post, new { id = "drawingForm" }))
{
<canvas id="myCanvas" width="352" height="352"
style="border: 1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<input type="hidden" name="imageData" id="imageData"/>
<input type="button" id="btnSave" value="Save Drawing"/>
}
[HttpPost]
public ActionResult SaveImage(CampaignViewModel model, string imageData)
{
//code.....
return RedirectToAction("Index", "Home");
}
We in ImindQ Online export the canvas as PNG with the following adapted code for your scenario:
In view:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Image</title>
</head>
<body>
<div>
#using (Html.BeginForm("SaveImage", "Campaign", FormMethod.Post, new { id = "drawingForm" }))
{
<canvas id="myCanvas" width="352" height="352"
style="border: 1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<input type="hidden" name="imageData" id="imageData" />
<input type="button" id="btnSave" value="Save Drawing" />
}
<script>
(function () {
document.getElementById('btnSave').addEventListener('click', function () {
var r = new XMLHttpRequest();
r.open("POST", "SaveImage", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
};
var p = document.getElementById('myCanvas').toDataURL('image/png').replace('data:image/png;base64,', '');
r.send(p);
});
})();
</script>
</div>
</body>
</html>
in Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace WebApplication2.Controllers
{
//public class CampaignViewModel
//{
// public string ImageData { get; set; }
//}
public class CampaignController : Controller
{
// GET: Campaign
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult SaveImage()
{
int len = (int)Request.InputStream.Length;
byte[] buffer = new byte[len];
int c = Request.InputStream.Read(buffer, 0, len);
string png64 = Encoding.UTF8.GetString(buffer, 0, len);
byte[] png = Convert.FromBase64String(png64);
System.IO.File.WriteAllBytes("d:\\a.png", png);
//string pngz = Encoding.UTF8.GetString(png, 0, png.Length);
//code.....
return RedirectToAction("Index", "Home");
}
//
}
}
in view :
#using (Html.BeginForm("SaveImage", "Campaign", FormMethod.Post, new { id = "drawingForm" }))
{
<canvas id="myCanvas" width="352" height="352"
style="border: 1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<input type="hidden" name="imageData" id="imageData"/>
<input type="button" onclick="saveimage(event)" id="btnSave" value="Save Drawing" />
<img style="display: none" src="images/ajax-loader/ajax-loader.gif" id="progressbar"/>
}
#*call action*#
<script>
function saveimage(event) {
#*prevent call back to server*#
event.preventDefault();
#*show progress bar *#
var progress = document.getElementById("progressbar");
$(progress).css('display', 'block');
#*get form data *#
var data = $("#drawingForm").serialize();
#*save image information to imageData tag *#
var image = document.getElementById("myCanvas").toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$("#imageData").val(image);
#*make ajax call *#
$.ajax({
url: "/Campaign/SaveImage",
data: data,
type: "Post",
dataType: "Json",
success: function (data) {
//do something
},
error: function (xhr, status, error) {
//do something
},
complete: function (data) {
$(progress).css('display', 'none');
}
});
}</script>
and in controller :
[HttpPost]
public ActionResult SaveImage(CampaignViewModel model, string imageData)
{
//path of folder taht you want to save the canvas
var path = Server.MapPath("~/images/canvaseimg");
//produce new file name
var fileName = GetPictureName(path);
//get full file path
var fileNameWitPath = Path.Combine(path, fileName);
//save canvas
using (var fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (var bw = new BinaryWriter(fs))
{
var data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
fs.Close();
}
//do somthing with model
return RedirectToAction("Index", "Home");
}
I am working on an MVC application and I can not understand why I am getting few values as 'null'.
What should be done to serialize the date value from JavaScript to C#.
View code:
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="mvcCRUDApp">
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("mvcCRUDApp", []);
app.service("crudAJService", function ($http) {
// save Customer
this.saveCustomer = function (objCustomer) {
var response = $http({
method: "post",
url: "Customer/PostDataResponse",
data: JSON.stringify(objCustomer),
dataType: "json"
});
return response;
}
});
app.controller("mvcCRUDCtrl", function ($scope, crudAJService) {
$scope.AddCustomer = function () {
var objCustomer = {
id: "0",
Name: $('#txtName').val(),
Surname: $('#txtSurname').val(),
BirthDate: $('#txtBirthDate').val(),
Gender: $('#txtGender').val(),
CityId: $('#drpCity').val()
};
var getBookData = crudAJService.saveCustomer(objCustomer);
getBookData.then(function (msg)
{
alert(msg.data);
}, function () {
alert('Error in updating book record');
});
}
});
</script>
<script>
$(document).ready(function ()
{
$("#drpState").change(function () {
$("#drpCity").empty();
$("#drpCity").append('<option value="0">-Select-</option>');
$.ajax({
type: 'POST',
url: '#Url.Action("SelectCities")',
dataType: 'json',
data: { Stateid: $("#drpState").val() },
success: function (cities) {
// cities contains the JSON formatted list
// of state id passed from the controller
$.each(cities, function (i, city)
{
$("#drpCity").append('<option value="'
+ city.id + '">'
+ city.Name + '</option>');
});
},
error: function (ex)
{
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
</head>
<body>
<div ng-controller="mvcCRUDCtrl">
<fieldset>
<table>
<tr><td>#Html.Label("Name")</td><td>#Html.TextBox("txtName")</td><td>#Html.Label("Surname")</td><td>#Html.TextBox("txtSurname")</td></tr>
<tr><td>#Html.Label("BirthDate")</td><td>#Html.TextBox("txtBirthDate")</td><td>#Html.Label("Gender")</td><td>#Html.TextBox("txtGender")</td></tr>
<tr>
<td>State</td>
<td>#Html.DropDownList("drpState", ViewBag.StateCollection as List<SelectListItem>)</td>
<td>City</td>
<td>#Html.DropDownList("drpCity", ViewBag.CityCollection as List<SelectListItem>)</td>
</tr>
<tr><td><input type="submit" value="Submit" ng-click="AddCustomer()" /></td></tr>
</table>
</fieldset>
</div>
</body>
</html>
Following is THE CODE OF CONTROLLER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DutchProject.Models;
namespace DutchProject.Controllers
{
public class CustomerController : Controller
{
DutchEntities db = new DutchEntities();
//
// GET: /Customer/
public ActionResult Index()
{
List<SelectListItem> States = new List<SelectListItem>();
var lstStates = db.States.ToList();
States.Add(new SelectListItem { Text = "-Select-", Value = "0" });
foreach (var item in lstStates)
{
States.Add(new SelectListItem { Text = item.Name, Value = item.id.ToString() });
}
ViewBag.StateCollection = States;
List<SelectListItem> Cities = new List<SelectListItem>();
Cities.Add(new SelectListItem { Text = "-Select-", Value = "0" });
ViewBag.CityCollection = Cities;
return View();
}
[HttpPost]
public JsonResult SelectCities(int Stateid)
{
IEnumerable<City> cities = db.Cities.Where(stat => stat.StateId == Stateid); // .Where(stat => stat.country_id == id);
return Json(cities);
}
[HttpPost]
public ContentResult PostDataResponse(Customer objCustomer)
{
objCustomer.BirthDate = DateTime.Now;
objCustomer.Gender = 1;
db.Customers.Add(objCustomer);
db.SaveChanges();
return Content("First name: " + Request.Form["firstName"] +
" | Last name: " + Request.Form["lastName"] +
" | Age: " + Request.Form["age"]);
}
}
}
ASP.NET MVC passes a null value in the controller action for a value that is not valid. It may help to validate the date beforehand, just to be sure the value is valid.
Also, it might help to assign a date instead of string:
...
var objCustomer = {
id: "0",
Name: $('#txtName').val(),
Surname: $('#txtSurname').val(),
BirthDate: new Date($('#txtBirthDate').val()),
Gender: $('#txtGender').val(),
CityId: $('#drpCity').val()
};
...
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 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();
}
}