2015-09-14 5 views
0

Я работаю с highcharts и листовки, и я хочу, чтобы мой скрипт обновлялся каждые 10 секунд без обновления всей страницы. Мне удалось сделать это с моим php-файлом highcharts, но когда я делаю то же самое со своим сценарием листка, ничего не происходит, карта не появляется. Я думаю, что проблема заключается в использовании функций, но почему это работает с highcharts, а не с лифтом.auto refresh javascript без загрузки всей страницы

Вот Highcharts PHP код файла

<div id="nb_tweets" style="width:100%; height:400px;"></div> 

<script> 

    $(function myFunction() 
    { 
     <?php include 'import_nb_tweets.php'; ?> 
     <?php include 'import_nb_users.php'; ?> 

     $('#nb_tweets').highcharts(
     { 
      chart: 
      { 
       type: 'line' 
      }, 
      title: 
      { 
       text: 'Number of tweets trend' 
      }, 
      xAxis: 
      { 
       categories: x_axis 
      }, 
      yAxis: 
      { 
       title: 
       { 
        text: 'Number of tweets' 
       } 
      }, 
      series: 
      [ 
       { 
        name: 'Precise geolocation', 
        data: nb_precise 
       } 
       , 
       { 
        name: 'Associated geolocation', 
        data: nb_associated 
       }, 
       { 
        name: 'All tweets', 
        data: nb_total 
       } 
      ] 
     }); 

     setTimeout(myFunction, 10000); 

    }); 

</script> 

И вот листовка код PHP File

<div id="map" style="width: 1300px; height: 650px"></div> 
 
    \t \t 
 
<script> 
 
    \t \t 
 
    $(function myFunction() { 
 
     
 
     // Inclusion of database variables 
 
     
 
      <?php include 'importDB_heat.php'; ?> 
 
      <?php include 'importDB2.php'; ?> 
 
      <?php include 'importDB3.php'; ?> 
 

 
      
 
     // Definition of the map variable and the default parameters 
 
     
 
      var map = new L.map('map', {fullscreenControl: true, fullscreenControlOptions: {position: 'topleft'}}).setView([53.350596, -6.303142], 14); 
 
     
 
      mapLink = '<a href="http://openstreetmap.org">OpenStreetMap</a>'; 
 
      
 
      L.tileLayer 
 
      (
 
       'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 
 
       { 
 
        attribution: '&copy; ' + mapLink + ' Contributors', 
 
        maxZoom: 18, 
 
       } 
 
      ).addTo(map); 
 
      
 
     
 
     // Definition of separate layers for markers and heat map and for precise and associated geolocation 
 
     
 
      var heat_layer_place = new L.LayerGroup(); 
 
      var heat_layer_precise = new L.LayerGroup(); 
 
      
 
      var precise_layer = new L.LayerGroup(); 
 
      var associated_layer = new L.LayerGroup(); 
 
     
 
     
 
     // Insertion (and defintion) of cluster groups in the markers layers 
 
     
 
      var markers_precise = new L.MarkerClusterGroup(); 
 
      markers_precise.addTo(precise_layer); 
 
      
 
      var markers_associated = new L.MarkerClusterGroup(); 
 
      markers_associated.addTo(associated_layer); 
 
     
 
     
 
     // Loading (and definition) of different icons for every marker layer - 
 
     
 
      var blueBird = L.icon({iconUrl: 'twitter_logo_blue.png', iconSize:[45,45], iconAnchor:[23,23], popupAnchor:[0,-19]}); 
 
      var redBird = L.icon({iconUrl: 'twitter_logo_red.png', iconSize:[40,40], iconAnchor:[23,23], popupAnchor:[0,-19]}); 
 
      
 
     
 
     // Insertion of heat layers on the map 
 
     
 
      var heat_place = L.heatLayer(quakePoints_place,{radius: <?php include 'par_map_rad.php'; ?>, blur: <?php include 'par_map_blur.php'; ?>, maxZoom: <?php include 'par_map_maxzoom.php'; ?>, }).addTo(map).addTo(heat_layer_place); 
 
      var heat_precise = L.heatLayer(quakePoints_precise,{radius: <?php include 'par_map_rad.php'; ?>, blur: <?php include 'par_map_blur.php'; ?>, maxZoom: <?php include 'par_map_maxzoom.php'; ?>, }).addTo(map).addTo(heat_layer_precise); 
 
     
 
     
 
     // Implementation (and insertion) of markers layers on the map 
 
     
 
      var nb_points = tweet_position.length; 
 
      
 
      for (var iter = 0; iter < nb_points; iter++) 
 
      { 
 
       markers_precise.addLayer(L.marker(tweet_position[iter],{title: tile_precise[iter], opacity: <?php include 'par_map_precise_op.php'; ?>, icon: blueBird}).bindPopup(texte_precise[iter])); 
 
      } 
 
      
 
      var nb_points_bis = tweet_place.length; 
 
      
 
      for (var iter = 0; iter < nb_points_bis; iter++) 
 
      { 
 
       markers_associated.addLayer(L.marker(tweet_place[iter],{title: tile_place[iter], opacity: <?php include 'par_map_associated_op.php'; ?>, icon: redBird}).bindPopup(texte_place[iter])); 
 
      } 
 
      
 
      map.addLayer(markers_precise); 
 
      map.addLayer(markers_associated); 
 
      
 
     
 
     // Definition (and insertion) of basic optional layers for the map 
 
     
 
      var osmLink = '<a href="http://openstreetmap.org">OpenStreetMap</a>'; 
 
      var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; 
 
      var osmAttrib = '&copy; ' + osmLink + ' Contributors'; 
 
      var osmMap = L.tileLayer(osmUrl, {attribution: osmAttrib}); 
 
      
 
      var thunLink = '<a href="http://thunderforest.com/">Thunderforest</a>'; 
 
      var \t landUrl = 'http://{s}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png'; 
 
      var thunAttrib = '&copy; '+osmLink+' Contributors & '+thunLink; 
 
      var landMap = L.tileLayer(landUrl, {attribution: thunAttrib}); 
 
      
 
      var EWI = '<a href="http://www.esri.com/">Esri</a>'; 
 
      var EWIUrl = 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'; 
 
      var EWIAttrib = '&copy; '+ EWI +'i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'; 
 
      var EWIMap = L.tileLayer(EWIUrl, {attribution: EWIAttrib}); 
 
      
 
      var transport = '<a href="http://openstreetmap.org">OpenStreetMap</a>'; 
 
      var transportUrl = 'http://{s}.tile.thunderforest.com/transport/{z}/{x}/{y}.png'; 
 
      var translink = '<a href="http://thunderforest.com/">Thunderforest</a>'; 
 
      var transportAttrib = '&copy; '+ transport +' Contributors & '+translink; 
 
      var transportMap = L.tileLayer(transportUrl, {attribution: transportAttrib}); 
 
     
 
      var baseLayers = {"OSM Mapnik": osmMap,"Landscape": landMap, "Esri World Imagery": EWIMap, "Transport": transportMap}; 
 
      var overlays = {"Tweet location: precise geolocation": precise_layer, "Tweet location: associated geolocation": associated_layer, "Tweet density: associated geolocation": heat_layer_place, "Tweet density: precise geolocation": heat_layer_precise}; 
 
      L.control.layers(baseLayers,overlays).addTo(map); 
 
      
 
      
 
     // Restriction of the result area of the search tool 
 
      
 
      var southWest = L.latLng(<?php include 'par_dublin_lat_SW.php'; ?>, <?php include 'par_dublin_long_SW.php'; ?>); 
 
      var \t northEast = L.latLng(<?php include 'par_dublin_lat_NE.php'; ?>, <?php include 'par_dublin_long_NE.php'; ?>); 
 
      var \t boundsOSM = L.latLngBounds(southWest, northEast); 
 
      var optionsOSM = {bounds: boundsOSM}; 
 
      
 
     
 
     // Insertion of the place search tool 
 
     
 
      var osmGeocoder = new L.Control.OSMGeocoder(optionsOSM); 
 
      map.addControl(osmGeocoder); 
 
      
 
      setTimeout(myFunction, 10000); 
 

 
    }); 
 
      
 
</script>

+0

Уверены ли вы, что у вас нет ошибок JavaScript? – Jacob

ответ

2

Это то, что запросы AJAX/XHR сделаны для. С его помощью вы можете получать данные в фоновом режиме и обновлять свои диаграммы/буклеты. Вот пример того, что вы можете сделать с AJAX/XHR:

Начиная с простой картой и группами для хранения маркеров в:

var map = L.map('leaflet', { 
    'center': [0, 0], 
    'zoom': 0, 
    'layers': [ 
     L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { 
      'attribution': 'Map data &copy; OpenStreetMap contributors' 
     }) 
    ] 
}); 

var group = new L.LayerGroup().addTo(map); 

Использования JQuery в $ .getJSON (функция преформ XHR GET запросы с данными JSON) вы можете запросить данные в фоновом режиме и использовать их на своей текущей карте. Я объясню через из кода в комментариях:

// Function for handling data 
function handle(response) { 
    // Empty the current layergroup 
    group.clearLayers(); 
    // Loop over the newly retreived array 
    response.forEach(function(value) { 
    // Add new marker to the group 
    group.addLayer(new L.Marker(value)); 
    }); 
} 

// Function for requesting new data 
function request() { 
    // Fetch url and execute handle function on success 
    $.getJSON('coordinates.json', handle); 
} 

// Immediately request new data 
request(); 
// Request new data every ten seconds 
setInterval(request, 10000); 

Вот рабочий пример на Plunker: http://plnkr.co/edit/qasIC2?p=preview (ум, он запрашивает те же данные снова и снова, так что позиции маркеров фактически не изменится, но я» вы добавляете несколько консольных сообщений, чтобы вы могли проверить их работоспособность). Вы легко можете адаптировать эту концепцию к тому, что вы пытаетесь сделать.

Смежные вопросы