I've developed an ASP.NET Core MVC 2 application to display markers on a map. The Model and Controller are as follows:
Model:
public class MarkersModel
{
public string title { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
Controller:
public class MarkersController : Controller
{
public IActionResult Index()
{
return View("Markers");
}
public IActionResult GetMarkers()
{
// Define landmarks, buildings, stops, and others
var model1 = new MarkersModel {lat = 53.43382, lng = 14.55559, title = "Galaxy"};
var model2 = new MarkersModel { lat = 53.42800, lng = 14.55124, title = "Kaskada" };
// Add more models here...
return Json(new {model1, model2 });
}
}
AJAX is used to retrieve data from the controller and store it in a variable called "response":
function getData() {
$.ajax({
url: '/Markers/GetMarkers',
type: 'POST',
dataType: "json",
data: JSON.stringify(),
contentType: 'application/json; charset=utf-8',
success: function(response) {
initMap(response);
},
error: function(error) {
alert('error');
}
The function initMap displays the JSON object in the console.log(data):
function initMap(data) {
console.log(data);
var map = new google.maps.Map(
document.getElementById('map'),
{ zoom: 10, center: { lat: 53.42894, lng: 14.55302 } });
// Parsing JSON data
var myMarkers = $.parseJSON(data);
}
How can I convert JSON to a Javascript array or add markers to the map?