3

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?

9
  • 1
    return View(ViewBag.sediList); - looks a bit strange. If you are using ViewBag and there is no model on View - you need return View(). If there is a model, containing the sediList - then you don't need a ViewBag. Just pass the data through the model Commented Dec 17, 2016 at 12:18
  • 1
    GetLatLon("@vb", function(location) - and here you pass string, but not an array Commented Dec 17, 2016 at 12:25
  • You need to assign it to a javascript variable - var vn = '@Html.Raw(Json.Encode(ViewBag.sediList))'; which will be an array of your 3 address strings. But change your code to delete ViewBag.sediList = sedi; and use return View(sedi); and in the view add @model List<string> then use '@Html.Raw(Json.Encode(Model))'; Commented Dec 17, 2016 at 12:29
  • 1
    @FabioBit System.Web.Mvc Commented Dec 17, 2016 at 12:54
  • 1
    @FabioBit, For mvc core, refer this answer Commented Dec 17, 2016 at 12:57

3 Answers 3

2

So you could create:

Model

public class MapsModel
{
    public MapsModel(string[] maps)
    {
        Maps = maps;
    }

    public string[] Maps { get; private set; }
}

Controller

public class MapsController : Controller
{
   // GET: MapsModel
   public ActionResult Index()
   {
        var model = new MapsModel(
                new[]
                {
                    "Via Gavinana, 19, Roma",
                    "Val de Seine, 94600 Choisy le Roi",
                    "Street 21,Shuwaikh, Kuwait"
                } 
            );

      return View(model);
   }
}

View

@model WebApplication1.Models.MapsModel

...

function initMap() {
   GetLatLon('@Html.Raw(Json.Encode(Model.Maps))', function (location) {

...

And you don't need ViewBag for such cases.

Sign up to request clarification or add additional context in comments.

19 Comments

You could try to use some 3rd-parties like '@Newtonsoft.Json.JsonConvert.SerializeObject(Model.Maps)'
because it returns string, but not HtmlString. There should be kind of HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Maps))... JsonHelper.Serialize should solve this issue as well. It should be a part of Asp.net core v5
GetLatLon('@(new HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Maps)))', function (location) {
What kind of string does it return? I have ["Via Gavinana, 19, Roma","Val de Seine, 94600 Choisy le Roi","Street 21,Shuwaikh, Kuwait"] for new HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(Model‌​.Maps))
It is just an array... var array = ["Via Gavinana, 19, Roma","Val de Seine, 94600 Choisy le Roi","Street 21,Shuwaikh, Kuwait"]; for (var s in array) { document.write(array[s]); }
|
0

You are not following the best approach but you can use this quick solution.

Controller:=>

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 = Json.Encode(sedi);

// No need to pass the viewbag in View param
return View();

View :=>

 var vb = @ViewBag.sediList;
 for(var i=0;i<vb.length;i++){
  GetLatLon (vb[i],function(){});
 }

 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);
        }
    });
  }

Comments

0

you must use it something like this: in your controller:

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");
var sediString = JsonConvert.SerializeObject(sedi);
ViewBag.sediList = sediString;
return View();

in your view put a hidden for using it in java script:

<input type="hidden" id="sediString" name="sediString" value="@ViewBag.sediList">

and in your java script use it like this:

var data = JSON.parse($("#sediString").val());

and you can have your data in array and use it in javascript each function:

$.each(data, function (i, item) {
//enter your code
}

Edit1: for javascript not jquery use:

var data = JSON.parse(document.getElementById(sediString).val());

instead of

var data = JSON.parse($("#sediString").val());

and use normal for instead of $.each

for (var i = 0; i < data.length; i++) {
       addMarker(data[i], map);
    }

Edit2:

you don't need hidden input for accessing view bag in java script. you can use it in javascript:

var data = JSON.parse(@ViewBag.sediList);

4 Comments

Can you rewrite it using "normal" javascript code and not jquery please?
Why do you use hidden fields here? This approach is not smth that should be used in MVC
@BorisSokolov because i want to have access to data that send from controller in my javascript. the data must be somewhere to have it in javascript
But it has access to Model or ViewBag in this sample.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.