user1400995
user1400995

Reputation:

ASP.NET MVC4 Razor in Javascript. Google Map not loading

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>

Upvotes: 1

Views: 1454

Answers (1)

karaxuna
karaxuna

Reputation: 26930

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.

Upvotes: 1

Related Questions