achencraft
achencraft

Reputation: 13

Multiple markers on Googe Map Api in MVC asp.net

I'm working about a web application in Asp.net MVC and i need to add multiple markers on Google Maps Api JavaScript.

In the View, I call a model which is a list of Vehicles Object.

<script>



function initMap() {

    var myLatLng = { lat: 48.584715, lng: 7.748556 };

    // Create a map object and specify the DOM element
    // for display.
    var map = new google.maps.Map(document.getElementById('carte'), {
        center: myLatLng,
        zoom: 14
    });

    // Create a marker and set its position.

    @foreach(var item in Model){
         <text>
              var marker = new google.maps.Marker({
              map: map,
              position: { lat: @item.VehicleLocation.Latitude, lng: @item.VehicleLocation.Longitude },
              title: 'Hello World!'
        </text>
        }

}</script>

I use the @foreach block to place a marker for each objet of the list.

Without this @foreach part, we can see the map. But when I put the @foreach, the map is not displayed.

I don't understand the problem

How can I solve it ?

Upvotes: 0

Views: 2847

Answers (2)

achencraft
achencraft

Reputation: 13

ok !

so the problem was in my object definition. Latitude and Longitude where double value, not string value. So coords where with a comma, and not a dot

I have add two string fields in my object, and i convert coords into it :

In the controller :

                foreach(var item in VehiculesList)
        {

            item.VehicleLocation.Lat_String = item.VehicleLocation.Latitude.ToString().Replace(",", ".");
            item.VehicleLocation.Long_String = item.VehicleLocation.Longitude.ToString().Replace(",", ".");
        }

In the View :

<script>



function initMap() {

    var myLatLng = { lat: 48.584715, lng: 7.748556 };

    // Create a map object and specify the DOM element
    // for display.
    var map = new google.maps.Map(document.getElementById('carte'), {
        center: myLatLng,
        zoom: 14
    });

    // Create a marker and set its position.

    @foreach(var item in Model){
         <text>
              var marker = new google.maps.Marker({
              map: map,
              position: { lat: @item.VehicleLocation.Lat_String, lng: @item.VehicleLocation.Long_String },
              title: 'Hello World!'
            });
        </text>

    }

}</script>

Upvotes: 1

Napoli
Napoli

Reputation: 1403

You are throwing a syntax error due to you not closing your google.maps.Marker(...) call.

@foreach(var item in Model){
     <text>
        var marker = new google.maps.Marker({
          map: map,
          position: { lat: @item.VehicleLocation.Latitude, lng: @item.VehicleLocation.Longitude },
          title: 'Hello World!'
        });
    </text>
}

Notice the closing });

Upvotes: 2

Related Questions