Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ASP.NET MVC Project and Google Maps: How to fill JavaScript array with values from C# List<>

I have a Class like this:

public class Markers
    {
        public double latitude { get; set; }
        public double longitude { get; set; }

        //Constructors and Methods
        //(...)
    }

On my Controller I have an ActionResult with a List of Markers and I add latitude and longitude like this

 List<Markers> listM = new List<Markers>(); //NOTE: this is outside of my ActionResult, no problem with that.
 //(...)
 listM.Add(new Markers(value[0], value[1])); //NOTE: value[0] is my lat and value[1] is my longitude
 //(...)

And at the end i return my list to the View:

return (listM);

Now on the View, I need to access the data and fill an array so I can display the markers on my google map.

How to fill the array with markers in position lat, long from my list?

@using ProjectName.Models
@model List<Markers>

<html>
<head>...</head>
<body>...</body>
<script type="text/javascript">

//How can I add a GoogleMap Marker ?
var markersArray = [];
@foreach(var item in Model)
                {
                      //can't use google.maps.Marker inside this foreach =(
                }

</script>
</html>

NOTE: This is how I add a marker on that array with a click on the map.

function addMarker(location) {
                var marker = new google.maps.Marker({
                    draggable: true,
                    animation: google.maps.Animation.DROP,
                    position: location,
                    title: 'Bomb',
                    map: map,
                    icon: bomb
                });
                markersArray.push(marker);
            }

Question 2: Markers still doesn't show on map after @Leo Solution!

  <script type="text/javascript">
            var map;
            var geocoder;
            var markersArray = [];
            var geoMarker;

            var bomb = new google.maps.MarkerImage('Content/Images/Pins/bomb.png',           
            new google.maps.Size(32, 37), 
            new google.maps.Point(0, 0), 
            new google.maps.Point(22, 44) 
            );



            function initialize() {


                var mapOptions = {
                    center: new google.maps.LatLng(41.287739, -7.738992),
                    zoom: 16,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                };


                map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);


                @foreach(var item in Model)
                {
                    <text>
                    var locations = google.maps.LatLng('@item.latitude', '@item.longitude', false);
                addMarker(locations);
                   </text>
                }



                geocoder = new google.maps.Geocoder();

                for (var i = 0; i < markersArray.length; i++) {
                    markersArray[i].setMap(map);
                }


                geoMarker = new GeolocationMarker(map);
                geoMarker.setCircleOptions({ fillColor: '#808080' });
                google.maps.event.addListenerOnce(geoMarker, 'position_changed', function () {
                    map.setCenter(this.getPosition());
                    map.fitBounds(this.getBounds());
                });
                google.maps.event.addListener(geoMarker, 'geolocation_error', function (e) {
                    alert('There was an error obtaining your position. Message: ' + e.message);
                });

                geoMarker.setMap(map);

                google.maps.event.addDomListener(window, 'load', initialize);


                google.maps.event.addListener(map, 'click', function (event) {
                    addMarker(event.latLng);
                });


                google.maps.event.addListener(map, 'zoom_changed', function () {

                    var zoomLevel = map.getZoom();           
                    //map.setCenter(myLatLng);
                    document.getElementById('mapzoom').innerHTML = 'Zoom: ' + zoomLevel;
                });


            }


            function showAddress() {
                alert("Vai navegar para outro endereço!");
                var address = document.getElementById('txtAddress').value;
                geocoder.geocode({ 'address': address }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        map.setCenter(results[0].geometry.location);
                        var marker = new google.maps.Marker({
                            map: mp,
                            position: results[0].geometry.location
                        });
                    } else {
                        alert('error: ' + status);
                    }
                });

            }


            function addMarker(location) {
                var marker = new google.maps.Marker({
                    draggable: true,
                    animation: google.maps.Animation.DROP,
                    position: location,
                    title: 'Bomba',
                    map: map,
                    icon: bomb
                });
                markersArray.push(marker);
            }


            function setAllMap(map) {
                for (var i = 0; i < markersArray.length; i++) {
                    markersArray[i].setMap(map);
                }
            }


            function clearMarkers() {
                setAllMap(null);
            }

            function showMarkers() {
                setAllMap(map);
            }


            function deleteMarkers() {
                clearMarkers();
                markersArray = [];
            }


            function loadScript() {
                var script = document.createElement('script');
                script.type = 'text/javascript';
                script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' +
                    'callback=initialize';
                document.body.appendChild(script);
            }

            window.onload = loadScript;


            if (!navigator.geolocation) {
                alert('Your browser does not support geolocation');
            }


        </script>
like image 886
M. Coutinho Avatar asked Nov 01 '22 09:11

M. Coutinho


1 Answers

Try this.....

 <script>
    var markersArray = [];
    var _map = null;
    var _c = null;


    @foreach(var item in Model)
    {
         <text>
             markersArray.push(new google.maps.Marker({
                 draggable: true,
                 animation: google.maps.Animation.DROP,
                 position: new google.maps.LatLng('@item.latitude', '@item.longitude', false),
                 title: 'Whatever title',
                 map: _map
             }));
         </text>
     }
 </script>

Second Question

I had to carefully look at your code and found 3 problems...one of them you've already mentioned it. The other ones are that you are duplicating variable names and you are not instantiating a new object. Now change this....

      @foreach(var item in Model)
            {
                <text>
                var locations = google.maps.LatLng('@item.latitude', '@item.longitude', false);
            addMarker(locations);
               </text>
            }

to this....

        @foreach(var item in Model)
            {
                <text>
            addMarker(new google.maps.LatLng(parseFloat('@item.latitude'), parseFloat('@item.longitude')));
               </text>
            }

Let me know how it goes

like image 91
Leo Avatar answered Nov 12 '22 21:11

Leo