I'm using google api to show a map. In my controller I wrote the following c# code:
var sedi = new List<string>();
sedi.Add("Via Gavinana, 19, Roma");
sedi.Add("Val de Seine, 94600 Choisy le Roi");
sedi.Add("Street 21,Shuwaikh, Kuwait");
ViewBag.sediList = sedi;
return View(ViewBag.sediList);
In my view:
@{
var vb = (List<string>)ViewBag.sediList;
}
function GetLatLon (address, callback) {
console.log(address);
var location = new Array();
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
location = { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng() };
callback(location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function addMarker (location, map) {
var marker = new google.maps.Marker({
position: location,
map: map
});
}
function initMap() {
GetLatLon("@vb", function(location) {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: location
});
for (var i = 0; i < 3; i++) {
addMarker(location, map);
}
});
}
And I want show three markers on map corresponding to the location written in the list vb
But address has System.Collections.Generic.List1[System.String]
value and not the real value of the address.
How can I pass the list as parameter to the GetLatLon
function in Javascript? How can I fix?
EDIT
I need to show three marker on the map, foreach address. I write:
function GetLatLonByAddress (address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
location = { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng() };
return location;
console.log (location);
}
return;
});
}
function initMap() {
GetLatLon('@(new Microsoft.AspNetCore.Html.HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Maps)))', function(location) {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: location
});
for (var i = 0; i < 3; i++) {
addMarker('@(new Microsoft.AspNetCore.Html.HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Maps)))', map, i);
}
});
}
function addMarker (location, map, count) {
var locationArr = JSON.parse(location);
var marker = new google.maps.Marker({
position: GetLatLonByAddress(locationArr[count]),
map: map
});
}
Is it possible something like this? How can I fix?
var vn = '@Html.Raw(Json.Encode(ViewBag.sediList))';
which will be an array of your 3 address strings. But change your code to deleteViewBag.sediList = sedi;
and usereturn View(sedi);
and in the view add@model List<string>
then use'@Html.Raw(Json.Encode(Model))';