MuthaFury MuthaFury - 3 months ago 17
jQuery Question

Google Maps constantly calling API

I have this code to make it to update the markers, and yes it works fine but everytime it refresh, it calls Google Maps API, how can I make it call once, and update the markers only. I know there is guide out there and quite new to javascript, I tried but none works. Anyone can help with this?

var pokemon_name = "";
var pokemon_array = [];
var infoWindowContent = [];
var markers = [];
var pokeImage = [];
var markers_data = [];
var infos_data = [];
var icon_data = "";

jQuery(function($) {
// Asynchronously Load the map API
//callAPI();
var script = document.createElement('script');
script.src = "//maps.googleapis.com/maps/api/js?key=KEYHERE&callback=callAPI";
document.body.appendChild(script);
});

function callAPI() {

$.ajax({
type: 'POST',
url: 'getpoke.php',
dataType: 'json',
data: $("#refresh_form").serialize(),
cache: false,
contentType: false,
processData: false,
success:function(data) {

bounds = new google.maps.LatLngBounds();
mapOptions = {
mapTypeId: 'roadmap'
};

// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
initialize(data);
}
});

}

setInterval(function(){callAPI();}, 10000);

function deleteMarkers() {
markers = [];
infoWindowContent = [];
pokeImage = []
}

function initialize(data) {

deleteMarkers();

var pokedata = $.parseJSON(data);

$.ajax({
url : "pokemonlist.txt",
dataType: "text",
success : function (data) {
var lines = data.split('\n');

for(var i=0;i<lines.length;i++) {
var arr = lines[i].split('"');

pokemon_id = arr[1];
pokemon_img = arr[3];
pokemon_name = arr[4];
pokemon_id = pokemon_id.trim();
pokemon_img = pokemon_img.trim();
pokemon_name = pokemon_name.trim();

pokemon_array.push([ pokemon_id, pokemon_img, pokemon_name ]);
}


for (var i = 0; i < pokedata['data'].length; i++) {
for (var x = 0; x < pokemon_array.length; x++) {

if (pokemon_array[x][0] == pokedata['data'][i]['pokemonId']) {
pokemon_name = pokemon_array[x][2];
}
}

pokemon_up = pokedata['data'][i]['upvotes'];
pokemon_down = pokedata['data'][i]['downvotes'];
pokemon_lat = pokedata['data'][i]['latitude'];
pokemon_long = pokedata['data'][i]['longitude'];

if (pokemon_down >= pokemon_up) {

}
else {
//markers_data.push([pokemon_id, pokemon_img, pokemon_name ]);
markers.push([pokemon_name, pokemon_lat, pokemon_long ]);
}
}

// Info Window Content

var nowTime = Date.now();

for (var i = 0; i < pokedata['data'].length; i++) {
for (var x = 0; x < pokemon_array.length; x++) {
if (pokemon_array[x][0] == pokedata['data'][i]['pokemonId']) {
pokemon_name = pokemon_array[x][2];
}
}

pokemon_up = pokedata['data'][i]['upvotes'];
pokemon_down = pokedata['data'][i]['downvotes'];
pokemon_created = 1e3 * pokedata['data'][i]['created'],
p = pokemon_created + 900000 - nowTime;

hour_data = parseInt(p / 6e4 % 60),
sec_data = parseInt(p / 1e3 % 60);

if (hour_data.toString().length == 1) {
hour_data = "0" + hour_data;
}

if (sec_data.toString().length == 1) {
sec_data = "0" + sec_data;
}

pokemon_trainer_name = pokedata['data'][i]['trainerName'];

pokemon_time_expire = hour_data + ":" + sec_data;

text_write = "<h3>"+pokemon_name+"</h3><br>Source:"+pokemon_trainer_name+" <br><br>Time expire: <span id='expire_"+i+"'>"+pokemon_time_expire+"</span>";

if (pokemon_down >= pokemon_up) {

}
else {
infoWindowContent.push([text_write]);
text_write = "";
}
}

var pokeImage = [];

for (var i = 0; i < pokedata['data'].length; i++) {
for (var x = 0; x < pokemon_array.length; x++) {
if (pokemon_array[x][0] == pokedata['data'][i]['pokemonId']) {
pokemon_img = pokemon_array[x][1];
}
}

pokemon_up = pokedata['data'][i]['upvotes'];
pokemon_down = pokedata['data'][i]['downvotes'];

if (pokemon_down >= pokemon_up) {

}
else {
pokeImage.push([pokemon_img]);
}
}

// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;

// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0],
icon: pokeImage[i][0]
});

// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));

// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}

// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(16);
google.maps.event.removeListener(boundsListener);
});

}
});

}

Answer

That code is pretty chaotic. I'm not sure if it solves everything, but I can see where the main problem is.

First: var bounds must be inside function initialize.

For the rest, try this; just replace callAPI() by my function. I guess if your code didn't cause errors, this should fix your question.

var firstTimeLoaded = false;
// load the markers (from server)
function callAPI() {
  $.ajax({
    type: 'POST',
    url: 'getpoke.php',
    dataType: 'json',
    data: $("#refresh_form").serialize(),
    cache: false,
    contentType: false,
    processData: false,
    success:function(data) {
      // Display a map on the page.  Obviously this needs to be done only once.
      if(firstTimeLoaded == false) {
        firstTimeLoaded = true;
        mapOptions = {
          mapTypeId: 'roadmap'
        };
        map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
        map.setTilt(45);
      }
      initialize(data);
    }
  });
}
// this means the function callAPI() will be called, every 10 seconds.
setInterval(function(){callAPI();}, 10000);

...

function initialize(data) {
  bounds = new google.maps.LatLngBounds();
  ...
}