2014-12-23 4 views
0

Я начинаю начинать с jQuery и пытаюсь прочитать данные из файла JSON и заполнить информацию (такую ​​как координаты) на марке Google Maps.Заполнение маркеров Google Maps от JSON

Этот код работает нормально, но маркер не заполнен. Кто-нибудь может помочь мне разобраться с проблемой JSON?

$(document).on("pageinit", "#agents", function() { 
    var defaultLatLng = new google.maps.LatLng(-25.975769, 32.582499); // Default 
    if (navigator.geolocation) { 
     function success(pos) { 
      // Location found, show map with these coordinates 
      drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)); 
     } 

     function fail(error) { 
      drawMap(defaultLatLng); // Failed to find location, show default map 
     } 
     // Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds 
     navigator.geolocation.getCurrentPosition(success, fail, { 
      maximumAge: 500000, 
      enableHighAccuracy: true, 
      timeout: 6000 
     }); 
    } else { 
     drawMap(defaultLatLng); // No geolocation support, show default map 
    } 

    function drawMap(latlng) { 
     var myOptions = { 
      zoom: 10, 
      center: latlng, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 
     var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions); 


     //READ FROM JSON 
     $.getJSON('data/agents.json', function (data) { 
      $.each(data.markers, function (i, marker) { 
       var marker = new google.maps.Marker({ 
        position: Marker.LatLng(marker.latitude, marker.longitude), 
        map: map, 
        title: Marker.title(marker.latitude, marker.longitude), 
       }); 
      }).click(function() { 
       $('#map-canvas').gmap('openInfoWindow', { 
        'address': marker.address 
       }, this); 
      }); 
     }); 

JSON

{ 
    "markers": [{ 
     "latitude": -25.975769, 
     "longitude": 32.582499, 
     "title": "ACME Company", 
     "address": "my address 1" 
    }, { 
     "latitude": -25.977743, 
     "longitude": 32.579959, 
     "title": "XPTO Company", 
     "address": "my address 2" 
    }] 
} 
+1

код как вывешено не действует javascript (функция 'drawMap' не закрыта и не является начальным' $ (document) .on ("pageinit" '). – geocodezip

+1

что такое' Marker.title() '/'Marker.LatLng()'? –

+0

I может скопировать его неправильно. В карте Google появляется сообщение bu t не маркеры. Latlng Я считаю, что это внутренняя функция API. – Andre

ответ

2

Просто, чтобы уменьшить путаницу, я изменил название параметра маркера TOT marker_data (это на самом деле не требуется). Ваша проблема была в строках с позицией: и заголовок:.

... 
//READ FROM JSON 
$.getJSON('data_agents.json', function (data) { 
    $.each(data.markers, function (i, marker_data) { 
     var marker = new google.maps.Marker({ 
      position: new google.maps.LatLng(marker_data.latitude, marker_data.longitude), 
      map: map, 
      title: marker_data.title, 
     }); 
    }).click(function() { 
     $('#map-canvas').gmap('openInfoWindow', { 
      'address': marker_data.address 
     }, this); 
    }); 
}); 
... 

Маркеры объекты помещаются на карте, но я не проверял InfoWindow


EDIT: вот функционирующий пример

<style> 
    #map-canvas { 
    height: 500px; 
    } 
    .gm-style-iw{ /* infowindow */ 
    width: 200px; 
    } 
</style> 
<div id="map-canvas"></div> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script> 
<script> 
    $(document).ready(function() { 
    var defaultLatLng = new google.maps.LatLng(-25.975769, 32.582499); // Default 
    if (navigator.geolocation) { 
     function success(pos) { 
      // Location found, show map with these coordinates 
      drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)); 
     } 
     function fail(error) { 
      drawMap(defaultLatLng); // Failed to find location, show default map 
     } 
     // Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds 
     navigator.geolocation.getCurrentPosition(success, fail, { 
      maximumAge: 500000, 
      enableHighAccuracy: true, 
      timeout: 6000 
     }); 
    } else { 
     drawMap(defaultLatLng); // No geolocation support, show default map 
    } 
    function drawMap(latlng) { 
     var myOptions = { 
      zoom: 10, 
      center: latlng, 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     }; 
     var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions); 
     // place the infowindow. Invisible, without content. 
     var infowindow = new google.maps.InfoWindow({ 
      content: '', 
     }); 
     //READ FROM JSON 
     $.getJSON('data/agents.json', function (data) { 
      $.each(data.markers, function (i, marker_data) { 
       var marker = new google.maps.Marker({ 
        position: new google.maps.LatLng(marker_data.latitude, marker_data.longitude), 
        map: map, 
        title: marker_data.title, 
       }); 
       // when the client clicks on a marker we set the content and bind the position to the marker 
       google.maps.event.addListener(marker, 'click', function() { 
        infowindow.setContent(marker_data.address); 
        infowindow.setPosition(this.getPosition()) 
        infowindow.setMap(map); 
       }); 
      }); 
     }); 
    } 
    }); 
</script> 
Смежные вопросы