Loop with PHP + JavaScript - javascript

I'm trying to create a map with markers, those markers location and content are stored in a database.
Here it is my code:
<?php
$query_map = "SELECT * FROM denuncias ORDER BY id";
$map_executa = mysql_query($query_map);
$lat = -1.456688;
$log = -48.477586;
?>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var map;
var center = new google.maps.LatLng(<?= $lat ?>, <?= $log ?>);
function init() {
var mapOptions = {
zoom: 13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
<?php while ($map = mysql_fetch_object($map_executa)) { ?>
var contentString = '<div id="content" style="height: 200px;">'+
'<div id="siteNotice">'+
'</div>'+
'<h3 id="firstHeading" class="firstHeading"><?= $map->titulo ?></h3>'+
'<div id="bodyContent">'+
'<?= $map->descricao ?>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 400
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(<?= $map->lat ?>, <?= $map->log ?>),
map: map,
clickable: true,
title: 'teste'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
<?php } ?>
}
google.maps.event.addDomListener(window, 'load', initialize);
//]]>
</script>
I'm able to get the markers at their correct positions, but the content is always the same: the last row.
Can anyone help me?
Thanks!
Delivered source code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
<title>Ver denúncias</title>
<!-- CSS -->
<style type="text/css">
body {
background: #3f51b5 !important;
}
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var map;
var center = new google.maps.LatLng(-1.456688, -48.477586);
function init() {
var mapOptions = {
zoom: 13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var contentString = '<div id="content" style="height: 200px;">'+
'<div id="siteNotice">'+
'</div>'+
'<h3 id="firstHeading" class="firstHeading">Nanana</h3>'+
'<div id="bodyContent">'+
'Teste'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 400
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(-1.458780, -48.480526),
map: map,
clickable: true,
title: 'teste'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
var contentString = '<div id="content" style="height: 200px;">'+
'<div id="siteNotice">'+
'</div>'+
'<h3 id="firstHeading" class="firstHeading">Teste 2</h3>'+
'<div id="bodyContent">'+
'AAAAAAAAAAAAAAAAAAA'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 400
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(-1.471875, -48.494237),
map: map,
clickable: true,
title: 'teste'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
//]]>
</script> <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
</head>
<body onload="init();">
<nav class="indigo no-pad-bot" role="navigation">
<div class="container" class="parallax-container">
<div class="nav-wrapper"><a id="logo-container" href="#" class="brand-logo"></a>
<ul id="nav-mobile" class="right side-nav no-pad-bot">
<li>Início</li>
<li>Ver denúncias</li>
<a class="waves-effect waves-light btn-large fazerdenuncia" style="margin-top: 5px; float: right !important">Fazer denúncia</a>
</ul><i class="mdi-navigation-menu"></i>
</div>
</div>
</nav>
<div class="section no-pad-bot no-pad-top white" id="index-banner">
<div class="row">
<div class="col s12 m8">
<h1>Places to check out in Zagreb</h1>
<section id="sidebar">
<div id="directions_panel"></div>
</section>
<section id="main">
<div id="map_canvas" style="width: 100%; height: 500px;"></div>
</section>
</div>
<div class="col s12 m4 barra flow-text">
<h1>
Últimas denúncias
</h1>
<!-- últimas denuncias -->
<div class="row">
<div class="col s10 m10 offset-s1 offset-m1 z-depth-2 grey lighten-3" id="ultimas-denuncias">
<h2 class="flow-text">
Nanana </h2>
<h2 class="flow-text">
Teste 2 </h2>
</div>
</div>
<div class="col s10 m10 offset-s1 offset-m1">
<p class="ultimos120">Nos últimos 120 dias</p>
<div class="text-center">
<h5 class="flow-text">55 denúncias feitas</h5>
<h5 class=" flow-text">25 denúncias resolvidas</h5>
</div></div>
<!-- fim últimas denúncias -->
</div>
</div>
</div>
<footer class="page-footer grey lighten-2">
<div class="container">
<div class="row">
<div class="col l6 s12">
<h5 class="black-text">Sobre este site</h5>
<p class="black-text text-lighten-1">
Esse site é mantido estudantes do ensino médio para lallalallala. <br> Caso queira contribuir para o projeto, clique aqui para fazer uma doação.
</p>
</div>
<div class="col l3 s12">
<h5 class="black-text">Links úteis</h5>
<ul>
<li><a class="black-text" href="#!">Link 1</a></li>
<li><a class="black-text" href="#!">Link 2</a></li>
<li><a class="black-text" href="#!">Link 3</a></li>
<li><a class="black-text" href="#!">Link 4</a></li>
</ul>
</div>
</div>
</div>
<div class="footer-copyright">
<div class="container">
<span class="black-text">Feito por</span> <a class="pink-text" href="http://www.mat3.us">mat3.us</a>
</div>
</div>
</footer>
<!-- Scripts-->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="js/materialize.js"></script>
<script src="js/init.js"></script>
</body>
</html>
Got to make the 2 texts appear, however, both of them appears on the same marker!
<?php
$query_map = "SELECT * FROM denuncias ORDER BY id";
$map_executa = mysql_query($query_map);
$lat = -1.456688;
$log = -48.477586;
$Count = 0;
$i = 0;
?>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var map;
var center = new google.maps.LatLng(<?= $lat ?>, <?= $log ?>);
function init() {
var mapOptions = {
zoom: 13,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
<?php while ($map = mysql_fetch_object($map_executa)) {
++$Count; ?>
var contentString<?= $Count ?> = '<div id="content" style="height: 200px;">'+
'<div id="siteNotice">'+
'</div>'+
'<h3 id="firstHeading" class="firstHeading"><?= $map->titulo ?></h3>'+
'<div id="bodyContent">'+
'<?= $map->descricao ?>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString<?= $Count ?>,
maxWidth: 400
});
var infowindow1 = new google.maps.InfoWindow({
content: contentString1,
maxWidth: 400
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(<?= $map->lat ?>, <?= $map->log ?>),
map: map,
clickable: true,
title: 'teste'
});
<?php } ?>
google.maps.event.addListener(marker, 'click', function() {
// Aqui!!!
infowindow.open(map,marker);
infowindow1.open(map,marker);
infowindow2.open(map,marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
//]]>
</script>
Have I done something wrong?

Try to fetch the Object first and then do a foreach Loop:
<?php
$Count = 0;
$map = mysql_fetch_object($map_executa) :
foreach($map as $marker)) {
++$Count; //This adds 1 to Count every time ?>
var contentString = '<div id="content" style="height: 200px;">'+
'<div id="siteNotice">'+
'</div>'+
'<h3 id="firstHeading" class="firstHeading"><?= $marker->titulo ?></h3>'+
'<div id="bodyContent">'+
'<?= $marker->descricao ?>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 400
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(<?= $marker->lat ?>, <?= $marker->log ?>),
map: map,
clickable: true,
title: 'teste'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
<?php } ?>
A foreach Loop has a better Performance too. See http://php.net/manual/en/control-structures.foreach.php for more Information.
Edit:
You have to Options:
1) Create a new Variable every time; You just need a Count:
var infowindow<?php echo count;?> = new google.maps.InfoWindow({
content: contentString,
maxWidth: 400
});
2) Use an Array: (Im not exactlly sure about the Array Syntax in JS)
infowindow() = new google.maps.InfoWindow({
content: contentString,
maxWidth: 400
});
and then call the window with
google.maps.event.addListener(count, marker, 'click', function() {
infowindow(count).open(map,marker);
});
You Need to create an Array for the markers to not just for the infowindows

As you are creating the info window object for each iteration, it will always display the last value because it is overriding the object. Try to place the below code outside the while loop and let me know if you have any issues.
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 400
});
Thank you

Related

Google Maps api show grey screen

I am trying to get on my website the gmaps with few markers but i am getting the grey screen or partially grey screen.Before, I used google maps API the same way and everythings works fine. If you can help me I would be grateful.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Zadanie 7</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDPAizH-vug5nDhwYi0C5Km-pCiQRx7wpY"></script>
</head>
<body>
<div class="container-fluid" id="map" style="height: 500px;">
</div>
<div class="container-fluid">
<div class="row content">
<div class="col-sm-3 sidenav">
<h4>Zadanie 6 Martin Kranec</h4>
<ul class="nav nav-pills nav-stacked">
<li>Prvá Stránka</li>
<li>Druhá Stránka</li>
<li class="active">Tretia Stránka</li>
</ul><br>
</div>
<div class="container-fluid">
<div class='container-fluid'><div class='table-responsive'><table class='table'><thead><tr><th>Vlajka</th><th>Štát</th><th>Počet Navštevníkov</th></tr></thead><tbody><tr><td>World</td><td>World</td><td>2</td></tr><tr><td><img class='flag' src='http://www.geonames.org/flags/x/sk.gif'></td><td><a href='countrystatistics.php?countrycode=sk'>Slovensko</a></td><td>2</td></tr></tbody></table></div></div> </div>
</div>
</div>
<footer class="container-fluid">
<p>&COPY;Martin Kranec Webové technológie</p>
</footer>
<script type='text/javascript'>
var lat=[];
var lon=[];
lat.push(48.15);
lon.push(17.1167);
lat.push(48.1704);
lon.push(17.4209);
</script>
<script>
function initMap() {
//alert(lat[1]);
var mapProp = {
center: new google.maps.LatLng(89, -25),
zoom: 4,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapProp);
var count = lat.length;
for (var i = 0; i < count; i++) {
var myLatLng = {lat: lat[i], lng: lon[i]};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: ''
});
}
}
initMap();
//initMap();
</script>
<!--<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDPAizH-vug5nDhwYi0C5Km-pCiQRx7wpY&callback=initMap"></script>-->
</body>
</html>
and here is my website where I work on this project http://147.175.98.165/zadanie7/thirdpage.php
Google maps has a lot of race conditions. I use this code a lot to display them instead. This code should be in a ready event like jquery ready.
new Promise(function (resolve, reject) {
if (!document.getElementById('google-maps')) {
var fileref = document.createElement('script');
fileref.setAttribute("type", "text/javascript");
var link = "https://maps.googleapis.com/maps/api/js?key=AIzaSyDPAizH-vug5nDhwYi0C5Km-pCiQRx7wpY&callback=mapsFinishedLoading";
fileref.setAttribute("async", "async");
fileref.setAttribute("defer", "defer");
fileref.setAttribute("src", link);
fileref.setAttribute("id", 'google-maps');
window.mapsFinishedLoading = resolve;
document.getElementsByTagName("body")[0].appendChild(fileref);
} else {
resolve();
}
}).then(function (result) {
//Your map should be available now
mapOptions={};//put your options here
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
});
Make sure your map div is visible before calling
var map = new google.maps.Map(document.getElementById('map'), mapOptions);

Change dropdown value after Google Maps Api marker click

i hope all of you are having a great day.
I come here with a question i have a form, with a dropdown menu with the list of locations of the company.
And below is my google maps api working. I get all the data from a previously received json from my api.
Im currently trying to make that when click on the map marker changes the value in the dropdown AGENCIA.
Heres the example of the form.
And here is the code, im almost there but i dont get it to work... right now i make an alert when i click on the marker to see if it the value is correct but when i click it the dropdown menu gets empty.
<?php
//Habilitar las sesiones
$codigoError ="";
session_start();
//Validar si existen las sesiones
if(!isset($_SESSION['vsJsonAgencias']))
{
header("location:../index.php");
}
//if(!empty($_SESSION['codigoError'])){
$codigoError = $_SESSION['codigoError'];
//}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="SGLabz">
<title>CitasWeb</title>
<!-- Bootstrap core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="../css/portfolio-item.css" rel="stylesheet">
<link rel="stylesheet" href="../css/form-basic.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script src="../js/form.js"></script>
<link href="../css/pikaday.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- date new-->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body >
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="#"><?php echo '<img alt="LOGO" height="40" width="40" src="http://'.$_SESSION['vsApache'].'/citasweb/icon.png"" >';?>CitasWeb</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<!-- Portfolio Item Row -->
<form class="form-basic" id="form-basic" <?php echo 'action="http://'.$_SESSION['vsApache'].'/citasweb/gestAgenciafunc.php"';?> method="post">
<div class="form-title-row">
<h1>Seleccionar</h1>
</div>
<div class="form-row">
<label>
<span>Gestión</span>
<?php
echo '<select name="codgestion">';
$jsonData =$_SESSION['vsJsonAgencias'];
$jsonDataObject = json_decode($jsonData);
foreach($jsonDataObject->TipoGestion as $option){
echo '<option value=' . $option->ID . '>' . $option->Nombre . '</option>';
}
echo '</select>';
?>
</label>
</div>
<div class="form-row">
<label>
<span>Fecha</span>
<input input type="text" id="datepicker" name="fecha" required/>
</label>
</div>
<div class="form-row">
<label>
<span>Agencia</span>
<?php
echo '<select id="agencia" name="agencia">';
//$jsonData = $_SESSION['vsJsonAgencias'];
$jsonData = file_get_contents('https://api.myjson.com/bins/t222l');
$jsonDataObject = json_decode($jsonData);
foreach($jsonDataObject->Agencias as $option){
echo '<option value=' . $option->ID . '>' . $option->Nombre . '</option>';
//CAPTURAR NOMBRE DE LA AGENCIA
$_SESSION['vsNomagencia'] = $option->Nombre;
}
echo '</select>';
?>
</label>
</div>
<body onload = "loadMap()">
<h2>Agencias</h2>
<?php
//$jsonData = file_get_contents('https://api.myjson.com/bins/t222l');
$jsonDataObject = json_decode($jsonData);
?>
<center>
<div id = "map" style = "width:480px; height:480px;"></div>
<script>
// fake JSON call
function getJSONMarkers() {
var markers = <?php echo $jsonData ?>;
return markers;
}
function loadMap() {
// Initialize Google Maps
const mapOptions = {
center:new google.maps.LatLng(13.706360,-89.212204),
zoom: 10
}
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Usted esta aquí.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
const map = new google.maps.Map(document.getElementById("map"), mapOptions);
// Load JSON Data
const data = getJSONMarkers();
// Initialize Google Markers
for(agencia of data.Agencias) {
let marker = new google.maps.Marker({
id: agencia.ID,
map: map,
position: new google.maps.LatLng(agencia.Latitud, agencia.Longitud),
content: agencia.Nombre,
})
marker.info = new google.maps.InfoWindow({
content: agencia.Nombre
});
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
marker = this;
alert('ID is :'+ this.id);
$(document).ready(function(){
$("#agencia").val(this.id);
});
});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyD-h6xw5-2X2DdSmL93dQmrR7p63Q_uv5w"></script>
</body></center>
<div class="form-row">
<button type="submit" >Consultar Horarios</button>
</div>
<center>
<?php
//print_r($_SESSION['codigoError']);
print_r( $codigoError);
?>
<br>
</center><br/>
<?php echo '<img alt="SALIR" height="42" src="http://'.$_SESSION['vsApache'].'/citasweb/php/regresar.png"" width="142">';?>
</form>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
<!-- Footer -->
<footer class="py-5 bg-dark">
<div class="container">
<?php echo '<center><img alt="SALIR" height="50" width="170" src="http://'.$_SESSION['vsApache'].'/citasweb/conticsa.png"" ></center><br/>';?>
<p class="m-0 text-center text-white">Copyright © Citas Web 2017</p>
</div>
<!-- /.container -->
</footer>
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/popper/popper.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="../js/pikaday.js"></script>
<script src="../js/moment.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker();
$.datepicker.regional['es'] = {
closeText: "Cerrar",
prevText: "<Ant",
nextText: "Sig>",
currentText: "Hoy",
monthNames: [ "Enero","Febrero","Marzo","Abril","Mayo","Junio",
"Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre" ],
monthNamesShort: [ "ene","feb","mar","abr","may","jun",
"jul","ago","sep","oct","nov","dic" ],
dayNames: [ "domingo","lunes","martes","miércoles","jueves","viernes","sábado" ],
dayNamesShort: [ "dom","lun","mar","mié","jue","vie","sáb" ],
dayNamesMin: [ "D","L","M","M","J","V","S" ],
weekHeader: "Sm",
dateFormat: "dd/mm/yy",
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: "" };
$.datepicker.setDefaults($.datepicker.regional['es']);
} );
</script>
</body>
</html>
Thanks in advance..
The problem's with the $(document).ready - it is not required:
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
marker = this;
alert('ID is :'+ this.id);
//----$(document).ready(function(){
$("#agencia").val(this.id);
//----});
});

Google map content not displaying inside Bootstrap modal part 2

Hello Stackoverflow Coders, I have created another google map with a form input that collects users address and populates it on a map. I have followed a correction created in this link below
Google map content not showing inside Bootstrap modal view
but still yet I cannot get the map to display inside a modal view. If run it on a normal page it will be okay.
can someone help me with that?
Thanks
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://maps.google.com/maps/api/js?libraries=places&region=ng&language=en&sensor=true&key=AIzaSyAlb3bRgk_Jq3mBzgpVyLTeeKL-RKaSkx4"></script>
</head>
<body>
<div class="container">
<h2>Google Map</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open MAP</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<br> Address:
<input id="searchTextField" type="text" size="50" style="">
<br>
<div id="test" style="height: 300px;width: 100%;margin: 0.6em;"></div>
<!-- MAP -->
<script type="text/javascript">
$(function getMap() {
var lat = 13.034118,
lng = 77.5679959;
latlng = new google.maps.LatLng(lat, lng),
image = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png';
//zoomControl: true,
//zoomControlOptions: google.maps.ZoomControlStyle.LARGE,
var mapOptions = {
center: new google.maps.LatLng(lat, lng),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.TOP_left
}
},
map = new google.maps.Map(document.getElementById('test'), mapOptions),
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image
});
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input, {
types: ["geocode"]
});
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(autocomplete, 'place_changed', function(event) {
infowindow.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
moveMarker(place.name, place.geometry.location);
$('.MapLat').val(place.geometry.location.lat());
$('.MapLon').val(place.geometry.location.lng());
});
google.maps.event.addListener(map, 'click', function(event) {
$('.MapLat').val(event.latLng.lat());
$('.MapLon').val(event.latLng.lng());
infowindow.close();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"latLng": event.latLng
}, function(results, status) {
console.log(results, status);
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
var lat = results[0].geometry.location.lat(),
lng = results[0].geometry.location.lng(),
placeName = results[0].address_components[0].long_name,
latlng = new google.maps.LatLng(lat, lng);
moveMarker(placeName, latlng);
$("#searchTextField").val(results[0].formatted_address);
}
});
});
function moveMarker(placeName, latlng) {
marker.setIcon(image);
marker.setPosition(latlng);
infowindow.setContent(placeName);
//infowindow.open(map, marker);
}
});
</script>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Tiles may not load if your map canvas is invisible when map is initializd.But you can trigger tiles loading by using resize.Since you are using you need to first store a reference to map object.
map = new google.maps.Map(document.getElementById('test'), mapOptions),
tmp = map;
And call resize event on map when your modal gets shown
$('#myModal').on('shown.bs.modal', function () {
google.maps.event.trigger(tmp, 'resize')
})

Googlemap Javascript error

I'm getting the 'Oops! Something went wrong' message when trying to run this Googlemap. The map code worked fine when I was developing it in isolation (see 'mymap.php' file below), but it's only after I have integrated it into my html template that this has happened. I've tried moving it around and running the javascript both inside and outside the head tags but it doesn't seem to make a difference.
I thought it might be an issue with the API key, but seeing as it works fine in the 'mymap.php' file I reckon that mustn't be it.
Could it be with the fact that I have placed the Javascript to create the map into the head tag? Or is the Bootstrap header maybe interfering in some way?
mymap.php (which works fine):
<!DOCTYPE html>
<?php
include("includes/db.php");
include("functions/functions.php");
// Create connection
$conn = new mysqli("localhost","root","","lstest1");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
if (isset ($_GET['loc_value'])) {
$locations = array(); // empty array to store location information
$county = $_GET['loc_value']; // which county are we going to map
$get_county = "select * from locations where county='$county'";
$result = $conn->query($get_county);
while ($row_locations = mysqli_fetch_assoc($result)){
$loc_name = $row_locations['loc_name'];
$latitude = $row_locations['latitude'];
$longitude = $row_locations['longitude'];
$description = $row_locations['loc_desc'];
$newLocation = array ("title" => $loc_name, "lat" => $latitude, "lng" => $longitude, "description" => $description);
array_push($locations, $newLocation);
}//while
}//if
//print_r($locations);
?>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var locations = <?php echo json_encode($locations, JSON_PRETTY_PRINT); ?>;
window.onload = function() {
LoadMap();
}
function LoadMap() {
var mapOptions = {
center: new google.maps.LatLng(54.6990782, -6.6171596),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
for (var i = 0; i < locations.length; i++) {
var data = locations[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent("<div style = 'width:200px;min-height:40px'>" + data.description + "</div>");
infoWindow.open(map, marker);
});
})(marker, data);
latlngbounds.extend(marker.position);
}
}//loadmap
</script>
<div class="map-responsive" id="map" style="width: 600px; height: 500px;"></div>
This is it placed within the Bootstrap template I am using - filename 'countymap.php':
<!DOCTYPE html>
<?php
include("includes/db.php");
include("functions/functions.php");
// Create connection
$conn = new mysqli("localhost","root","","lstest1");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
if (isset ($_GET['loc_value'])) {
$locations = array(); // empty array to store location information
$county = $_GET['loc_value']; // which county are we going to map
$get_county = "select * from locations where county='$county'";
$result = $conn->query($get_county);
while ($row_locations = mysqli_fetch_assoc($result)){
$loc_name = $row_locations['loc_name'];
$latitude = $row_locations['latitude'];
$longitude = $row_locations['longitude'];
$description = $row_locations['loc_desc'];
$newLocation = array ("title" => $loc_name, "lat" => $latitude, "lng" => $longitude, "description" => $description);
array_push($locations, $newLocation);
}//while
}//if
//print_r($locations);
?>
<html lang="en">
<!-- Arvo font for webpage & font-awesome-->
<link href='https://fonts.googleapis.com/css?family=Arvo' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="fonts/font-awesome/css/font-awesome.min.css">
<link href='https://fonts.googleapis.com/css?family=Rubik' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Stoke' rel='stylesheet' type='text/css'>
<head>
<title>Location Scout</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<!-- Custom styles for this template -->
<link href="styles/location.css" rel="stylesheet">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Map</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var locations = <?php echo json_encode($locations, JSON_PRETTY_PRINT); ?>;
window.onload = function() {
LoadMap();
}
function LoadMap() {
var mapOptions = {
center: new google.maps.LatLng(54.6990782, -6.6171596),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var latlngbounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
for (var i = 0; i < locations.length; i++) {
var data = locations[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent("<div style = 'width:200px;min-height:40px'>" + data.description + "</div>");
infoWindow.open(map, marker);
});
})(marker, data);
latlngbounds.extend(marker.position);
}
}//loadmap
</script>
</head>
<body>
<div class="container-fluid text-center">
<!-- MAIN HEADING AREA -->
<div class="row">
<div class="col-md-12">
<h1>
LOCATION SCOUT
</h1>
</div>
</div>
<!-- MAIN ACTIVITY WINDOW -->
<div class="row">
<div class="col-md-9">
<div class="map-responsive" id="map" ;"></div>
</div>
<!-- SIDEBAR/MENU AREA -->
<div class="col-md-3">
<div class="btn-group-vertical">
Homepage
User Page
</div>
<div class="container">
<div class="row">
<div class="form col-md-3">
<form method="get" action="results.php">
<input type="text" name="user_query" placeholder="Search for location"/>
<input type="submit" name="search" value="search"/>
</form>
</div>
</div>
</div>
<h2>Welcome!</h2>
<p>
This is your one-stop shop to plan your visit to some of Northern Ireland's most fascinating movie and Tv locations.
Start your search on the menus below or use the search box above to get plotting!
</p>
<h2>Start your search:</h2>
<div class="btn-group">
<button type="button" class="btn btn-warning">By County</button>
<button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>
Antrim
</li>
<li>
Armagh
</li>
<li>
Down
</li>
<li>
Fermanagh
</li>
<li>
Londonderry
</li>
<li>
Tyrone
</li>
</ul>
</div><br>
<div><br></div>
<div class="btn-group">
<button type="button" class="btn btn-warning">By Genre</button>
<button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>
Drama
</li>
<li>
Thriller
</li>
<li>
Documentary
</li>
<li>
Horror
</li>
<li>
Sci-fi
</li>
<li>
Children
</li>
<li>
Fantasy
</li>
</ul>
</div><br>
<div><br></div>
<div class="btn-group">
<button type="button" class="btn btn-warning">By Production</button>
<button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>
Game of Thrones
</li>
<li>
Line of Duty
</li>
<li>
The Fall
</li>
</ul>
</div><br>
<div><br></div>
<div class="btn-group">
Login
Register
</div><br>
<br><div class="btn-group">
Admin
</div>
</div>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
<script src="js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>

Google map api v3 shows half a map?

I'm doing a project in Jquery Mobile and having a problem with the Google API. When I navigate to the MapPage from diffrent page the MapPage by itself shows the map OK, but when moving from the HomePage to MapPage it only shows half of the map. If I manually refresh or resize map it will fix it - but I've tried map.resize() without luck so I need a different solution.
I've attached my HTML code of the HomePage and MapPage below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="description" content="Project - Mobile" />
<meta name="author" content="Yuval Vardi" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RentAcar</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<script src="JS/jquery-2.0.2.js"></script>
<script src="JS/jquery.mobile-1.3.1.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="JS/mapScript.js" > </script>
</head>
<body>
<div id="HomePage" data-role="page" data-add-back-btn="true">
<div data-role="header">
</div>
<div data-role="content">
Trip Info
</div>
<div data-role="footer" class="mainFooter">
<h2> © Copyright Yuval Vardi </h2>
<p class="yearNow"> </p>
</div>
</div>
<div id="calculate" data-role="page" data-add-back-btn="true">
<div data-role="header">
</div>
<div data-role="content">
<table id="mapTable">
<tr>
<td>
<p>Pickup location</p>
</td>
<td></td>
<td>
<p>Where do you go?</p>
</td>
</tr>
<tr>
<td>
<input id="startInput" type="text" value="" placeholder="Start location" />
</td>
<td></td>
<td>
<input type="text" id="end" placeholder="Return location"/>
</td>
</tr>
<tr>
<td data-role="controlgroup">
<button id="myLocation" onclick="getMarker()" data-role="button" data-theme="e" > Find me </button>
</td>
<td></td>
<td data-role="controlgroup">
<button onclick="calcRoute()" data-theme="b" > Calculate rout </button>
</td>
</tr>
<tr>
<td colspan="3">
<div id="map-canvas" style="width:400px; height:280px;">
</div>
</td>
</tr>
</table>
</div>
<div data-role="footer" class="mainFooter">
<h2> © Copyright Yuval Vardi </h2>
<p class="yearNow"> </p>
<a class="ui-btn-right" href="#HomePage" data-role="button" data-icon="home" data-iconpos="top" >Home</a>
</div>
</div>
</body></html>
My javascript file:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var israel = new google.maps.LatLng(32.0938254, 34.7786934); // the var for our initial point
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: israel // where to center the map on initial!
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
initialize();
var start = document.getElementById('startInput').value;
var end = document.getElementById('end').value;
var distanceInput = document.getElementById("distance");
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
distanceInput.value = response.routes[0].legs[0].distance.value / 1000;
}
});}
google.maps.event.addDomListener(window, 'load', initialize);
function getMarker() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition,showError);
}
}
function showPosition(position) {
var lat=position.coords.latitude;
var long=position.coords.longitude;
marker(lat,long); //calls the marker function
}
function showError(error)
{
alert ("Error loading map");
}
function marker(lat,long) {
var myLatlng = new google.maps.LatLng(lat,long);
var mapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
$("#startInput").attr("value",myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"You are Here!"
});
}
The map div has zero width. To use a percentage width, you have to define the width of all its parents (or at least up to a fixed size element that can be used to compute the width).
See Mike Williams' Google Maps API v2 tutorial page on percentage sizing
You need to call checkResize() API function. Like This:
map = new google.maps.Map(document.getElementById("map"), mapOptions);
map.checkResize()
This one worked for me as well

Categories