5

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>
1
  • well constructed question Commented Dec 13, 2013 at 7:08

1 Answer 1

2

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

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

11 Comments

Can't use var location, but i changed it to another name. Markers doesn't show on map. Maybe because im not initializing map with them, ill check that.
Well, I was actually trying to provide some guidance of how to use razor syntax inside a script block, you still have to adjust this code. I'll update it for you
Well i think i have some problem with my data! It works now, but with other values! Example: "var locations = new google.maps.LatLng(-25.363882, 131.044922);" Your help was truly useful, thank you! It seems I need to understand better how to work with coordinates. Thank you sir!
Google Map doesn't show markers when i add values from my model item.longitude and item.latitude. Do you have any ideas why? Already created an alert('item.longitude') and the value is correct :S
I noticed you are using the experimental version and after reviewing the documentation I cannot find any MarkerImage object in the documentation reference. It doesn't exist
|

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.