1

I am having some issues with the setMarkers() function and my map is not displayed at all. I presume that I'm doing something wrong with the Razor syntax within the setMarkers function. Could you please suggest a solution? As I'm not an expert in this technology, is it normal to mix Razor within Javascript functions or should I follow an alternative better practice, i.e move my script functions within the @section featured scope? Thanks in advance

My MarkerModel:

public class MarkerModel
    {
        public string Description { get; set; }
        public double latitude { get; set; }
        public double longitude { get; set; }
        public int zIndex { get; set; }
    }

My View:

@model IEnumerable<DAssistant.Web.Models.MarkerModel>

<style type="text/css">
    #map-canvas
    {
        height: 500px;
    }
</style>

@{
    ViewBag.Title = "Map"; 
}

@section featured {
    <div id="map-canvas"></div>
}

<script type="text/javascript" src="http://www.google.com/jsapi?autoload={'modules':[{name:'maps',version:3,other_params:''}]}"></script>
<script type="text/javascript">

    function init() {
        var mapDiv = document.getElementById('map-canvas');

        var mapOptions = {
            center: new google.maps.LatLng(-33.890542, 151.274856),
            zoom: 8,
            mapTypeControl: true,
            zoomControl: true,
            scaleControl: true,
            streetViewControl: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }

        var map = new google.maps.Map(mapDiv, mapOptions);

        setMarkers(map);
    }

    function setMarkers(map) {

        @foreach (var item in Model)
        {
            <text>
            var myLatLng = new google.maps.LatLng(@item.latitude, @item.longitude);
            var marker = new google.maps.Marker({
                position: myLatLng,
                map: map,
                title: @item.Description,
                zIndex: @item.zIndex
            });
            </text>
        }
    }
    google.maps.event.addDomListener(window, 'load', init);
</script>
3
  • <div id="map-canvas"></div>, I think this should be in your body, correct me if i'm wrong Commented Jul 4, 2014 at 5:58
  • Any errors in browser dev tools? The foreach doesn't look right. It's defining the same variables over and over. Commented Jul 4, 2014 at 6:00
  • There are no errors in Chrome javascript Console Commented Jul 4, 2014 at 6:07

1 Answer 1

1

Change this:

title: @item.Description

To:

title: '@item.Description'

For example description is 'some string', then title would be:

title: some string

That is not valid javascript.

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

1 Comment

Thanks it was the string issue :)

Your Answer

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