Show coordinates on a google map with jquery Asp.Net MVC

2

Hi, I have a project in asp.net mvc which brings some coordinates of the database and should show the markers on a map, but it does not. Here I leave the code and the result in the browser console.

@model Models.VerRutaModel

<style type="text/css">
    #map {
        height: 100%;
    }
</style>

<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close fa fa-close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title" id="VerRutaModal">Ruta </h4>
</div>
<div class="modal-body" style="height: 400px;">
<div id="map"></div>
</div>
<div class="modal-footer text-right">
<button type="button" class="btn btn-primary" data-dismiss="modal">Aceptar</button>
</div>
</div>
</div>

<script type="text/javascript">
    
var locations = [],
center = new google.maps.LatLng(10, 20);

function initialize() {
@foreach (RutaRastreo ruta in Model.RutaRastreo)
{
if (ruta.Gps_Latitud != 0 && ruta.Gps_Longitud != 0)
{
@:locations.push([@ruta.Gps_Latitud, @ruta.Gps_Longitud]);
}
}  
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();
var marker,
    i,
    position,
    bounds = new google.maps.LatLngBounds();

for (i = 0; i < locations.length; i++) {
position = new google.maps.LatLng(locations[i][1], locations[i][2]);
marker = new google.maps.Marker({
position: position,
map: map
});

bounds.extend(position); // añado la posición a bounds
console.log(position);

google.maps.event.addListener(
     marker,
    "click",
    (function (marker, i) {
    return function () {
    infowindow.setContent(locations[i][0]);
    infowindow.open(map, marker);
    };
  })(marker, i)
 );
}
map.fitBounds(bounds); 
}
   initialize();
</script>

}
}
    

Use estos dos metodos para eliminar las "," en las coordendas, pero el resultado fue el mismo

locations = locations.map((elemento) => {
    return [
       elemento[0], 
       Number(elemento[1] + '.' + elemento[2]), 
       Number(elemento[3] + '.' + elemento[4])
    ];
});
O bien, en ES5

locations = locations.map(function(elemento) {
    return [
       elemento[0], 
       Number(elemento[1] + '.' + elemento[2]), 
       Number(elemento[3] + '.' + elemento[4])
    ];
});

    
asked by Huntzberger 03.11.2018 в 02:09
source

1 answer

1

Disclaimer: I have never used asp.net-mvc so I have no idea of the usefulness of the <text> tag but this answer should be the same.

Let's start from the end back to the beginning.

First:

When you declare your markers, you want to associate to each one a listener that when clicking on the marker opens the infowindow with a content locations[i][0] . This makes me think that in reality your locations are not google.maps.LatLng ni google.maps.LatLngLiteral but arrays made up of

[ruta.comentario, ruta.Gps_Latitud, ruta.Gps_Longitud]

In that case, locations is an array of arrays and the center of the map should be declared independently. For example using a google.maps.LatLngLiteral :

var locations=[],
    center = { lat: 10, lng: 20};

Or a google.maps.LatLng

var locations=[],
    center = new google.maps.LatLng(10, 20);

Because the center of a map can be either a LatLng or a LatLngLiteral (see MapOptions documentation )

Second , in each iteration redefines locations as an array containing an object google.maps.LatLng

locations = [new google.maps.LatLng(@ruta.Gps_Latitud, @ruta.Gps_Longitud)];

At the end of the loop, locations will only contain the last object google.maps.LatLng .

Actually what you want is to have an array of arrays with the form

[
    [ruta.comentario, ruta.Gps_Latitud, ruta.Gps_Longitud],
    [ruta.comentario, ruta.Gps_Latitud, ruta.Gps_Longitud],
    [ruta.comentario, ruta.Gps_Latitud, ruta.Gps_Longitud]
]

So instead of redeclare you have to add elements to locations :

 var locations = [];

@foreach (TablaRuta ruta in Model.Ruta)  {
  if (ruta.Gps_Latitud != 0 && ruta.Gps_Longitud != 0)     {
     locations.push([@ruta.comentario, @ruta.Gps_Latitud, @ruta.Gps_Longitud]);
  }
}

After which you will have an array of arrays.

With those modifications, the rest of the code should work. There is, however, a bad practice in the middle, and that is that your function initialize has a parameter locations that makes shadowing of the global variable. As a good practice, you should give the parameter another name to distinguish whether we are talking about the global variable or the parameter, or omit the parameter completely, because the function already has access to locations in the global scope.

Bonus Track

Suppose you do not know the center of the map in advance, and you want to deduce it from the markers that are going to be drawn. In that case, you can create a google.maps.LatLngBounds element and expand it with each added marker, to then tell the map to adopt a position and zoom that contains the markers, using the method fitBounds :

var marker, 
      i, 
      position, 
      bounds = new google.maps.LatLngBounds();

  for (i = 0; i < locations.length; i++) {
    position = new google.maps.LatLng(locations[i][1], locations[i][2]);
    marker = new google.maps.Marker({
      position: position,
      map: map
    });

    bounds.extend(position); // añado la posición a bounds

    google.maps.event.addListener(
      marker,
      "click",
      (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        };
      })(marker, i)
    );
  }

  map.fitBounds(bounds);

Or if you want to keep the zoom of the map and only modify your center based on the markers:

 map.setCenter(bounds.getCenter());

Edit

Since the coordinates apparently come from the backend using comma as a decimal separator, it means that locations is being declared as if it were, for example:

var locations = [
    ['casa', 3,33654, 2,35454],
    ['trabajo', 4,54825, 8,47574]
];

Javascript interprets the comma as a separator between elements of an array, so arrays of 5 elements are formed, as if you were declaring:

var locations = [
    ['casa', 3, 33654, 2, 35454],
    ['trabajo', 4, 54825, 8, 47574]
];

Since .replace is a method of string , in javascript, probably within an asp.net loop it can not be applied. In that case, the solution would be that after filling the array:

@foreach (TablaRuta ruta in Model.Ruta)  {
  if (ruta.Gps_Latitud != 0 && ruta.Gps_Longitud != 0)     {
     locations.push([@ruta.comentario, @ruta.Gps_Latitud, @ruta.Gps_Longitud]);
  }
}

locations was refined using the .map method that the arrays have, in the form:

locations = locations.map((elemento) => {
    return [
       elemento[0], 
       Number(elemento[1] + '.' + elemento[2]), 
       Number(elemento[3] + '.' + elemento[4])
    ];
});

Or, in ES5

locations = locations.map(function(elemento) {
    return [
       elemento[0], 
       Number(elemento[1] + '.' + elemento[2]), 
       Number(elemento[3] + '.' + elemento[4])
    ];
});
    
answered by 03.11.2018 / 17:54
source