M
M
Max2015-05-18 23:39:40
JavaScript
Max, 2015-05-18 23:39:40

How to output JSON data?

Hello, please tell me how you can display data from a Json file in Google Maps.
There is a file in JSON in which 10 stops are allowed. Each stop consists of 12 coordinates. Here is an example of coordinates for one of the stops.

"coords" : []

Here is the script with which I pulled other data to output to the table before
$(function() {
  	$.getJSON('zones.json', function(data){
  		var template = $('#my_stops').html();
  		var html = Mustache.to_html(template, data);
  		$('#info').html(html)
  });
  });

And here is the Google Map code where I manually inserted the coordinates of one of the stops into the new.google.maps.Latlng fields
function initialize_map( ) {
     var latlng = new google.maps.LatLng(49.25100320801442,28.541126489672024);
     var myOptions = {
     zoom: 18,
     center: latlng,
     mapTypeId: google.maps.MapTypeId.ROADMAP
     };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    var polygonCoords = [
   	  new google.maps.LatLng(49.25156346163994,28.542151093515713),
   	  new google.maps.LatLng(49.25113626882619,28.542376399072964),
   	  new google.maps.LatLng(49.25074759018555,28.541657567056973),
   	  new google.maps.LatLng(49.25076509829823,28.54119622710641),
   	  new google.maps.LatLng(49.25100320801442,28.541126489672024)
   	 ];
   	 var polygon = new google.maps.Polygon({
   	  path: polygonCoords,
   	  strokeColor: "#5196DB",
   	  strokeOpacity: 1,
   	  strokeWeight: 2,
   	  fillColor: "#8ab9e7",
   	  fillOpacity: 0.5
   	 });
   	 polygon.setMap(map);   
   	 return map;
   }


The question is, how do I put the coordinates from the JSON file into positions
new google.maps.LatLngfor the remaining 10 stops. Moreover, in the future, the number of stops should increase.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kovpashko, 2015-05-29
@sainttechnik

Remove the first stop from map initialization.
Then something like this:

$(function() {
  $.getJSON('zones.json', function(data){
    var map = initialize_map();
    // проходимся по остановках
    $.each(data.coords, function(index, polyCoords){
      // преобразуем массив с координатами каждой точки в массив из LatLng
      var path = $.map(polyCoords, function(pointCoords){
        return new google.maps.LatLng(pointCoords[0], pointCoords[1]);
      });

      // добавляем полигон
      var polygon = new google.maps.Polygon({
        map: map, // ваша карта
        path: path,
        strokeColor: "#5196DB",
        strokeOpacity: 1,
        strokeWeight: 2,
        fillColor: "#8ab9e7",
        fillOpacity: 0.5
      });
    });
  });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question