Carregar vários maps do google na mesma página
Saudações senhoras e senhores, e estou com uma pequena dificuldade..
Preciso fazer várias requisições de vários mapas conforme os ips coletados, e a configuração para pegar as coordenadas de latitude e longitude pelo IP eu já consegui fazer, mas só gera um mapa e os outros ips correspondentes ele não aparece, pois sei que preciso criar uma requisição para carregar de cada ip um mapa, e deixei um link disponível para vocês terem ideia .
LINK PARA O TESTE DO MAPA DO GOOGLE
No link acima é a maneira como eu pretendo, mas só aparece o primeiro mapa e vejam que as coordenadas é de acordo com cada IP, e sou ciente que essas localizações não são exatas por se tratar de IPS dinâmicos.
SEGUE O CÓDIGO QUE ESTOU USANDO PARA O SISTEMA !
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#form_2').submit(function(){
beforeSend:$("#new_carregando").fadeIn(900);
var dados = jQuery( this ).serialize();
jQuery.ajax({
type: "POST",
url: "deletar_visitantes_online.php",
data: dados,
success: function( data ){
if(data){
alert(data);
complete:$("#new_carregando").fadeOut(1400);
}else if(data){
alert("ok");
window.self.location.href ="visitas.php";
complete:$("#new_carregando").fadeOut(1400);
}
}
});
return false;
});
});
</script>
<?php
include_once("config.php");
// A sessão precisa ser iniciada em cada página diferente
if (!isset($_SESSION)) session_start();
$session =$_SESSION['UsuarioUSUARIO'];
header( 'Content-Type: text/html; charset=utf-8' );
header( "Cache-Control: no-cache, must-revalidate" );
header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
// Verifica se não há a variável da sessão que identifica o usuário
//recebemos o parametro vindo do ajax
if($_POST['page']){
//configurações da pagina
$page = $_POST['page'];
$cur_page = $page;
$page -= 1;
$per_page = 10;
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;//inclui o arquivo de conexão
//instanciamos nossa classe
//executamos nossa query
$sql = $MySQLi->query("SELECT id FROM visitantes_online ORDER BY id DESC LIMIT 10") or print(mysqli_error());
$total = mysqli_num_rows($sql);
$total_max=$total=10;/ calcula a quantidade de produtos sendo exibidos no momento /
$query =$MySQLi->query("SELECT * FROM visitantes_online LIMIT ".$start.",".$per_page."");
$Quant = mysqli_num_rows($query);
?>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 80%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<?php// create a new cURL resource
// fim da Função do contador de visitas com banco de dados //
function getPage($url, $referer='', $timeout=30, $header=''){
if ($referer=='') $referer='http://'.$_SERVER['HTTP_HOST'];
if(!isset($timeout)) $timeout=30;
$curl = curl_init();if(strstr($referer,"://")){
curl_setopt ($curl, CURLOPT_REFERER, $referer);
}
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt ($curl, CURLOPT_USERAGENT, sprintf("Mozilla/%d.0",rand(4,5)));
curl_setopt ($curl, CURLOPT_HEADER, (int)$header);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
$html = curl_exec ($curl);
curl_close ($curl);
return $html;
}
?>
<form action="" method="POST" id="form_2" name="apaga" enctype="multipart/form-data">
<div class="visitas_botao">
<input type="hidden" name="Quantidade" id="Quantidade" value="<?php echo $total_max; ?>">
<input type="submit" name="button" id="button" value="Apagar">
<input type="reset" name="button2" id="button2" value="Cancelar">
<input type="checkbox" name="chkAll" onClick="checkAll(this)"><b>Selecionar Tudo</b>
</div>
// AQUI COMEÇA O CÓDIGO PARA PEGAR AS COORDENADAS E EXIBIR O MAPA USANDO O CURL E O WHILE PARA BUSCAR TODOS OS IPS ARMAZENADOS //
<?php
$i = 10;
while($result = mysqli_fetch_array($query)) {
$id=$result['id'];
$ip = $result['ip_usuario'];
$data = $result['tempo_sessao'];
echo "<br />
";
//// guarda uma copia do xml no seu servidor
$ch = curl_init("http://ip-api.com/xml/".$ip."");
$fp = fopen("feedcache.xml", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
// carrega o arquivo, porém agora local
$xml = simplexml_load_file("feedcache.xml");
$subs = $xml->feed->entry['circulation'];//---
$dados['sucesso'] =(string) $xml ->status;
$dados['rua'] = (string) $xml ->country;
$dados['bairro'] = (string) $xml->region;
$dados['cidade'] = (string) $xml ->regionName;
$dados['estado'] = (string) $xml ->city;
$dados['zip'] = (string) $xml ->zip;
$dados['latitude'] = (string) $xml ->lat;
$dados['longitude'] = (string) $xml ->lon;
$dados['timezone'] = (string) $xml ->timezone;
$dados['provedor'] = (string) $xml ->isp;
$dados['empresa'] = (string) $xml ->org;
$dados['estado'] = (string) $xml ->as;
$dados['IP'] = (string) $xml ->query;
?>
<script>
// This example displays a map with the language set to Arabic and the
// regions set to Egypt. These settings are specified in the HTML script
// element when loading the Google Maps JavaScript API.
// Setting the language shows the map in the language of your choice.
// Setting the region biases the geocoding results to that region.
// In addition, the page's html element sets the text direction to
// right-to-left.
function initMap() {
var cairo = {lat: <?php echo $dados['latitude']?>, lng:<?php echo $dados['longitude']?>};
var map = new google.maps.Map(document.getElementById('map'), {
scaleControl: true,
center: cairo,
zoom: 18
});
var infowindow = new google.maps.InfoWindow;
infowindow.setContent('<b>MAPA</b>');
var marker = new google.maps.Marker({map: map, position: cairo});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAQiIvxtURMaZKpE6Tj6hyJdfC72kgQI3g&callback=initMap"
async defer></script>
//*** FIM DA PARTE DE BUSCA DOS MAPAS ***//
<div class="visitas_botao"><?php echo $id;?>
<input type="checkbox" name="del_" value="<?php echo $id; ?>" />
<font color="#999">IP: </font><b> <?php echo $ip; ?></b> <span style="padding:10px;margin-left:100px;color:#003366"><b> Data <?php echo $data; ?> | LATITUDE:<?php echo $dados['latitude']?> | LONGITUDE<?php echo $dados['longitude']?></b></span>MAPA: <div id="map" style="width:70%; height:300px"></div><?php echo $i++;?>
</div>
<?php
}
?>
<br /><div class="visitas_botao">
<input type="hidden" name="Quantidade" id="Quantidade" value="<?php echo $total_max; ?>">
<input type="submit" name="button" id="button" value="Apagar">
<input type="reset" name="button2" id="button2" value="Cancelar">
<input type="checkbox" name="chkAll" onClick="checkAll(this)"><b>Selecionar Tudo</b>
</div></form>
<?php
/ --------------------------------------------- /
//contamos quantos resgistros possui para controle dos botões
$resultado2 = $MySQLi->query("SELECT COUNT(*) AS count FROM visitantes_online");
if(count($resultado2)){
foreach ($resultado2 as $res2) {
$count = $res2['count'];
}
}
//desconecta do banco
$no_of_paginations = ceil($count / $per_page);
/ ---------------Calculando a valores inicial e final para o loop----------------------------------- /
if ($cur_page >= 4) {
$start_loop = $cur_page - 1;
if ($no_of_paginations > $cur_page + 3)
$end_loop = $cur_page +4;
else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
$start_loop = $no_of_paginations - 4;
$end_loop = $no_of_paginations;
}else{
$end_loop = $no_of_paginations;
}
}else{
$start_loop = 1;
if($no_of_paginations > 6)
$end_loop = 6;
else
$end_loop = $no_of_paginations;
}
/ ----------------------------------------------------------------------------------------------------------- /
$msg .= "<div class='pagination'><ul><br />";
// para habilitar o primeiro botão
if ($first_btn && $cur_page > 1) {
$msg .= "<li p='1' class='active'>Início</li>";
}elseif($first_btn) {
$msg .= "<li p='1' class='inactive'>Início</li>";
}
// Para permitir que o botão anterior
if ($previous_btn && $cur_page > 1) {
$pre = $cur_page - 1;
$msg .= "<li p='".$pre."' class='active'>Anterior</li>";
}elseif($previous_btn) {
$msg .= "<li class='inactive'>Anterior</li>";
}
for ($i = $start_loop; $i <= $end_loop; $i++) {
if ($cur_page == $i)
$msg .= "<li p='$i' id='pass_2' class='active'>{$i}</li>";
else
$msg .= "<li p='".$i."' class='active' id='pass'>{$i}</li>";
}
// Para permitir o botão próximo
if ($next_btn && $cur_page < $no_of_paginations) {
$nex = $cur_page + 1;
$msg .= "<li p='".$nex."' class='active'>Próximo</li>";
}elseif($next_btn) {
$msg .= "<li class='inactive'>Próximo</li>";
}
// Para ativar o botão final
if ($last_btn && $cur_page < $no_of_paginations) {
$msg .= "<li p='".$no_of_paginations."' class='active'>Última</li>";
}elseif($last_btn){
$msg .= "<li p='".$no_of_paginations."' class='inactive'>Última</li>";
}
$goto = '<input type="text" class="goto" size="1"/><input type="button" id="go_btn" class="go_button" value="Seguir"/>';
$total_string = "<div class='total' a='".$no_of_paginations."'>Página <b>" . $cur_page."</b> de <b>".$no_of_paginations."</b></div>";
$msg = $msg."".$goto.$total_string."</ul></div><br />";
// Content for pagination
//retornamos nossa var com nosso html feito
echo $msg;
}
?>
Tentei fazer as requisições com ajax para recarregar o script do google mas sem sucesso, mas se alguém tiver uma ideia de como fazer eu agradeçoDiscussão (6)
Carregando comentários...