1

Can someone please explain my possible options when trying to get razor data inside javascript? I am trying to add markers to google map.

This seems to work:

@model IEnumerable<ServicesPortal.Models.MapsPartialModel>
@{
    ViewBag.Title = "Home Page";
}

@if (Model != null)
{
    <script type="text/javascript"  src="http://maps.googleapis.com/maps/api/js?sensor=false">
    </script>
    <script type="text/javascript">
    function initialize() {
        var mapOptions = {
            center: new google.maps.LatLng(46.119944, 14.815333),
            zoom: 5,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map"), mapOptions);

        addmarker(46.119944, 14.815333);
        // and so on...

        function addMarker(x, y) {
            var location = new google.maps.LatLng(x, y);
            var marker = new google.maps.Marker({
                position: location,
                map: map,
            });
        }
    } google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    <div id="map" style="width:auto; height:500px"></div>
}

While this does not:

@model IEnumerable<ServicesPortal.Models.MapsPartialModel>
@{
    ViewBag.Title = "Home Page";
}

@if (Model != null)
{
    <script type="text/javascript"  src="http://maps.googleapis.com/maps/api/js?sensor=false">
    </script>
    <script type="text/javascript">
    function initialize() {
        var mapOptions = {
            center: new google.maps.LatLng(46.119944, 14.815333),
            zoom: 5,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map"), mapOptions);

        @foreach (var item in Model)
        {
            <text>
                addMarker(@item.Profile.lat, @item.Profile.lng);
            </text>
        }

        function addMarker(x, y) {
            var location = new google.maps.LatLng(x, y);
            var marker = new google.maps.Marker({
                position: location,
                map: map,
            });
        }
    } google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    <div id="map" style="width:auto; height:500px"></div>
}

EDIT: This is also not working...

@model IEnumerable<ServicesPortal.Models.MapsPartialModel>
@{
    ViewBag.Title = "Home Page";
}

@if (Model != null)
{
    <script type="text/javascript"  src="http://maps.googleapis.com/maps/api/js?sensor=false">
    </script>
    <script type="text/javascript">
    function initialize() {
        var mapOptions = {
            center: new google.maps.LatLng(46.119944, 14.815333),
            zoom: 5,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map"), mapOptions);

        @foreach (var item in Model)
        {
            <text>
               addMarker(@Html.Raw(item.Profile.lat), @Html.Raw(item.Profile.lng));
            </text>
        }

        function addMarker(x, y) {
            var location = new google.maps.LatLng(x, y);
            var marker = new google.maps.Marker({
                position: location,
                map: map,
            });
        }
    } google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    <div id="map" style="width:auto; height:500px"></div>
}

EDIT: Tried also with some variables ... no effect.

@model IEnumerable<ServicesPortal.Models.MapsPartialModel>
@{
    ViewBag.Title = "Home Page";
}

@if (Model != null)
{
    <script type="text/javascript"  src="http://maps.googleapis.com/maps/api/js?sensor=false">
    </script>
    <script type="text/javascript">
    function initialize() {
        var mapOptions = {
            center: new google.maps.LatLng(46.119944, 14.815333),
            zoom: 5,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map"), mapOptions);

        // test
        var lat = 46.119944;
        var lng = 14,815333;

        @foreach (var item in Model)
        {
           <text>
              addMarker(@lat, @lng);
           </text>
        }

        function addMarker(x, y) {
            var location = new google.maps.LatLng(x, y);
            var marker = new google.maps.Marker({
                position: location,
                map: map,
            });
        }
    } google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    <div id="map" style="width:auto; height:500px"></div>
}

I was trying to use this solution, but I am missing something... Using Razor within JavaScript

3 Answers 3

2

Your values contain a dot and Razor, in its brightness, interprets that as an object.property. Try using Html.Raw():

<text>addMarker(@Html.Raw(item.Profile.lat), @Html.Raw(item.Profile.lng));</text>
Sign up to request clarification or add additional context in comments.

4 Comments

Did your debug the foreach loop? Are you seeing the values in the Model?
yes. The values are there. Even if i make some variables containing the same values it doesnt work also.
Please set a debugger; breakpoint after the foreach loop to see what text was produced. Inspected with the developer tools available in your browser.
You're welcome. Just remember that whenever you have dots in your values, you're gonna have a bad time...
0
    @model IEnumerable<Advertise.ViewModel.Models.Address.AddressViewModel>

    <style>
        #markerClusterMapCanvas {
            height: 100%;
            width: 100%;
        }

    </style>

<div id="markerClusterMapCanvas"></div>
@if (Model != null)
{
    <script>
        var map;
        var locationMap = [];

        function initMapMarkerCluster() {

             map = new google.maps.Map(document.getElementById('markerClusterMapCanvas'),
            {
                zoom: 10,
                center: { lat: 35.6988196, lng: 51.3924643 }
            });

            var markers = locationMap.map(function(location, i) {
                return new google.maps.Marker({
                    position: location
                });
            });

            var markerCluster = new MarkerClusterer(map,
                markers,
                { imagePath: '/Content/GoogleMap/m' });





        }

@foreach (var item in Model)
            {
                <text>
                    addMarker(@item.Latitude, @item.Longitude);
                </text>
            }
        function addMarker(x, y) {
            locationMap.push({lat: x, lng: y});
        }
    </script>
    <script src="~/Scripts/GoogleMap/markerclusterer.js"></script>

    <script async defer
            src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCNquRLkvpmnKcTnyLvCIxt1oh-HRiQiMg&callback=initMapMarkerCluster">
    </script>
}

1 Comment

Add some explanation with answer for how this answer help OP in fixing current issue
0

I used Html.Raw to get markers and then put markers' lat, lng and some information inside 'locations'.

var locations = [
        @(Html.Raw("{" + string.Join("},{", Model.MarkersOfPlace.Select(m=> "lat:" + (m.Latitude).ToString().Replace(',', '.') + ",lng:" + (m.Longtitude).ToString().Replace(',', '.') + ",id:" + m.Id + ",placeName:'" + m.Name +  "'")) + "}" ))
    ]

I created an array of markers based on given locations array.

var markers = locations.map(function (location, i) {
            var marker = new google.maps.Marker({
                position: {lat: location.lat, lng: location.lng},
                id:location.id,
                title: location.placeName,
                clickable: true
            });
            marker.addListener('click', function() {
                //when clicked, do sth
            });
            return marker;
        });

Comments

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.