Why my google map is not showing? - json

i have tried almost everything but i am unable to correct my code.My code is not showing google map and markers on it. I have a sqlite3 db canberra.db from where i am getting the data.
canberra.db:
CREATE TABLE `markers` (
`city_id` INTEGER,
`name` TEXT,
`latitude` TEXT,
`longitude` TEXT,
`type` TEXT
)
Any help would be highly appreciated thanks in advance.
test.php:
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('canberra.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql=<<<EOF
SELECT * from markers;
EOF;
$result = $db->query($sql);
$json = array();
while($row = $result->fetchArray(SQLITE3_ASSOC) ){
echo $json[]['lat'] = $row['latitude'];
echo $json[]['lon'] = $row['longitude'];
echo $json[]['name'] = $row['name'];
echo $json[]['type'] = $row['type'];
}
$db->close();
echo "Operation done successfully\n";
?>
<script type="text/javascript">
function initMap() {
var locationsJSON = '<?php echo json_encode($json) ?>';
var locations = JSON.parse(locationsJSON);
var bounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker, i;
for (i = 0; i < locations.length; i++) {
console.log(locations[i]);
var myLatLng = new google.maps.LatLng(locations[i].lat, locations[i].lon);
bounds.extend(myLatLng);
map.fitBounds(bounds);
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
}
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDooxT39owZBkpRXCGKPbRuQd5fSkr0Xvk&callback=initMap">
</script>

Try var_dumping your $json array and you'll see what's wrong.
You can replace your while loop content with:
$json[] = array(
'lat' => $row['latitude'],
'lon' => $row['longitude'],
'name' => $row['name']
);

I have change this function and my code works :)
function initMap() {
debugger;
var locationsJSON = <?php echo json_encode($json, JSON_PRETTY_PRINT) ?>;
var locations = locationsJSON;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker, i;
for (i = 0; i < locations.length; i++) {
console.log(locations[i]);
var myLatLng = new google.maps.LatLng(locations[i].lat, locations[i].lon);
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
}
}
And one thing i also post php script at the top.
<?php
class MyDB extends SQLite3
?>
<!DOCTYPE html>
<html>
</html>
i hope this will help others.

You create your array with
echo $json[]['lat'] = $row['latitude'];
echo $json[]['lon'] = $row['longitude'];
echo $json[]['name'] = $row['name'];
But then you're referring to the coordinates with:
var myLatLng = new google.maps.LatLng(locations[i][1], locations[i][2]);
Change that to:
var myLatLng = new google.maps.LatLng(locations[i].lat, locations[i].lon);

Related

how to displaying multiple location on google map using php-mysql,js

i have to try to fetch lat ,lng value from db and encode results in json like this
[{"name":"ahmedabad,GUJ","lat":"72.5226896","lng":"72.5226896"}]
but marker not displaying on map(location not display on map)
this is my code, what are the my mistake please guide me
<?php
include "db.php";
/* lat/lng data will be added to this array */
$locations=array();
$query = $db->query("SELECT * FROM ds_petroling_history");
while( $row = $query->fetch_assoc() ){
$nama_kabkot = $row['name'];
$longitude = $row['lng'];
$latitude = $row['lat'];
/* Each row is added as a new array */
$locations[]=array( 'name'=>$nama_kabkot, 'lat'=>$longitude, 'lng'=>$longitude );
}
/* Convert data to json */
$markers = json_encode($locations);
?>
<html>
<head>
</head>
<body>
<div><?php echo $markers ?></div>
<script type='text/javascript'>
<?php
echo "var markers=$markers;\n";
?>
function initMap() {
var latlng = new google.maps.LatLng(23.0117523,72.5226665);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById("peta"),myOptions);
var infowindow = new google.maps.InfoWindow(), marker, lat, lng;
var json=JSON.parse( markers );
for( var o in json ){
lat = json[ o ].lat;
lng=json[ o ].lng;
name=json[ o ].name;
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
name:name,
map: map
});
google.maps.event.addListener( marker, 'click', function(e){
infowindow.setContent( this.name );
infowindow.open( map, this );
}.bind( marker ) );
}
}
</script>
<div id="peta" style="width: 100%; height: 660px;">
</div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=yourkey&callback=initMap"
type="text/javascript"></script>
</body>
</html>
value fetched from db successfully and encode in json also but not find those coordinates location on map
you have just assigned the values for markers to a php var not to a javascript var
/* Convert data to json */
$markers = json_encode($locations);
echo "<script>
var markers[] = " . $markers .";
</script>";
?>

Google Maps in Modal not centered

I'm using a Google Map in a modal. But it the center is not what I want.
I use following script:
<script>
function initMap() {
var lattp = <?php echo json_encode($lattp);?>;
var lngtp = <?php echo json_encode($lngtp);?>;
var zoomtp = <?php echo json_encode($zoomtp);?>;
var tp = {lat: JSON.parse(lattp), lng: JSON.parse(lngtp)};
var latrest = <?php echo json_encode($latrest);?>;
var lngrest = <?php echo json_encode($lngrest);?>;
var rest = {lat: JSON.parse(latrest), lng: JSON.parse(lngrest)};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: JSON.parse(zoomtp),
center: tp
});
var marker = new google.maps.Marker({
position: rest,
map: map
});}
$('#myModal').on('shown.bs.modal', function() {
google.maps.event.trigger(map, "resize");
map.setCenter(tp);
});
</script>
The result is not what I want. You can check it: https://www.checkjevoeding.be/uitstap/tp_rest_dishes.php?id=9
Just click on "Aanduiding parkplan"
You should move the map and tp out of the initMap() method as it is not accessible outside the method.
<script>
var map, tp;
function initMap() {
var lattp = <?php echo json_encode($lattp);?>;
var lngtp = <?php echo json_encode($lngtp);?>;
var zoomtp = <?php echo json_encode($zoomtp);?>;
tp = {lat: JSON.parse(lattp), lng: JSON.parse(lngtp)};
var latrest = <?php echo json_encode($latrest);?>;
var lngrest = <?php echo json_encode($lngrest);?>;
var rest = {lat: JSON.parse(latrest), lng: JSON.parse(lngrest)};
map = new google.maps.Map(document.getElementById('map'), {
zoom: JSON.parse(zoomtp),
center: tp
});
var marker = new google.maps.Marker({
position: rest,
map: map
});
}
$('#myModal').on('shown.bs.modal', function() {
google.maps.event.trigger(map, "resize");
map.setCenter(tp);
});
</script>

Mark multiple locations on google map with google map api

I want to add multiple locations on google map. I have saved the longtitude and latitude in the database. Then I retrieve it from PHP and append the the data to a Javascript function. When I hardcode the locations in Javascript, it works fine. But when I load the data with PHP it's not working. But when I check it with Firebug, it shows that the PHP values have come to the relevant places. The issue is that nothing is loading. The following is the code I up with.
<script type="text/javascript">
function initialize() {
<?php
$con=mysqli_connect("HOST","DBUSERNAME","DBPASSWORD","TABLE");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM locations");
?>
var count=0;
var my = new google.maps.LatLng(7.860661,80.674896);
var mapOptions = {
zoom: 8,
center: my
}
<?php while($row = mysqli_fetch_array($result))
{
?>
var myLatlng;
var finallatlang=myLatlng.concat(count.toString());
finallatlang = new google.maps.LatLng(<?php echo $row['latitude'];?>,<?php echo $row['longtitude'];?>);
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: finallatlang,
map: map,
title: '<?php echo $row['location_name'];?>'
});
count++;
<?php } ?>
mysqli_close($con);
?>
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Updated my code
function initialize() {
$result = mysqli_query($con,"SELECT * FROM locations");
?>
//var count=0;
<?php $count=0;?>
var my = new google.maps.LatLng(7.860661,80.674896);
var mapOptions = {
zoom: 8,
center: my
}
<?php while($row = mysqli_fetch_array($result))
{
?><?php echo $count++;?>
//var myLatlng;
<?php $mylatlang="mylatlang";?>
//var finallatlang=myLatlng.concat(count.toString());
//var count=parseInt(<?php //echo $count;?>);
//var finallatlang=myLatlng+count.toString();
finallatlang = new google.maps.LatLng(parseFloat(<?php echo $row['latitude'];?>),parseFloat(<?php echo $row['longtitude'];?>));
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var latlang='<?php echo $mylatlang+$count?>';
//var latlang=Math.random();
var marker = new google.maps.Marker({
position: latlang,
map: map,
title: '<?php echo $row['location_name'];?>'
});
//count++;
}
google.maps.event.addDomListener(window, 'load', initialize);
This is the final answer which i was come up with.Special thanks to Rorschach.
<div id="map" style="width: 1000px; height: 900px;"></div>
<script type="text/javascript">
<?php
$con=mysqli_connect("HOST","HOSTUSERNAME","HOSTPASSWORD","DATABASE");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM locations");
?>
var locations = [<?php while($row = mysqli_fetch_array($result))
{?>
['<?php echo $row['location_name'];?>', <?php echo $row['latitude'];?>, <?php echo $row['longtitude'];?>],
<?php }?>
];
var latlng = new google.maps.LatLng(6.934947,79.862308);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
myOptions);
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})
(marker, i));
}
Your problem is here (info in your 'answer', not yet in your question):
new google.maps.LatLng('6.936992','79.860935')
The LatLng constructor expects two floating point numbers, not two strings. If it were
new google.maps.LatLng(6.936992,79.860935)
you'd be fine. Use parseFloat to convert these values to floats:
finallatlang = new google.maps.LatLng(
parseFloat(<?php echo $row['latitude'];?>),
parseFloat(<?php echo $row['longtitude'];?>)
);
Your db connection(php code):
<?php $con=mysql_connect("host","dbuser","dbpassword");
mysql_select_db("dbname",$con);
$result = mysql_query("SELECT * FROM locations");
?>
Google map multiple markers (Javascript code) :
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var locations = [
<?php while($row = mysql_fetch_array($result)) { ?>
['marker 1',<?php echo $row["lat"] ?>,<?php echo $row["longs"] ?>, 4],
<?php } ?>
];
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
myOptions);
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})
(marker, i));
}
</script>

Google Maps Api Version 3 Auto-Zoom

I have a Problem i am a beginner in Google Maps and not really good in Java Script but in PHP. Is there a possibel Solution for an "Auto-Zoom" Function. I have different Markers on my Map an i want to Zoom automaticcaly to the level that every Marker is Visibel ?
Is there any Solution Please Help me !
Ok This is my Script:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCxuRdCmN2BO5PD7kwI0mO8JflcUOF4CtI&sensor=true">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(50.903033, 10.496063),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var markerBounds = new google.maps.LatLngBounds();
var contentString;
<? php
$i = 1;
foreach($FertigID as $ID) {
$result = mysql_query("SELECT * FROM Daten_CH WHERE ID = ".$ID."");
while ($Ergebnisse = mysql_fetch_array($result)) { // Werden alle ergebnisse (ID´s) in einen Array geschriebenn
if (isset($Ergebnisse["GIS_y"]) && $Ergebnisse["GIS_y"] != "" && $Ergebnisse["GIS_y"] != " ") { ?> contentString = '<input type="button" value="BEARBEITEN"></button>';
var Position = new google.maps.LatLng( <? php echo $Ergebnisse["GIS_y"]; ?> , <? php echo $Ergebnisse["GIS_x"]; ?> );
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker <? php echo $i; ?> = new google.maps.Marker({
position: Position,
map: map,
title: '<?php echo $Ergebnisse["AA_Objektname"]; ?>'
});
google.maps.event.addListener(marker <? php echo $i; ?> , 'click', function() {
infowindow.open(map, marker <? php echo $i; ?> );
});
<? php
}
}
$i++;
} ?>
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
What you want to do, is create a LatLngBounds object, use its extend method to extend the bounds with your markers (using LatLng objects), then use the fitBounds (or panToBounds if you want animation) of the Map object and the map will auto zoom to a position where it will show all your markers.
Here's some basic pseudocode:
// You create your map. You have to do this anyway :)
// The Map object has a lot of options, you specify them according to your needs.
var map = new google.maps.Map(document.getElementById('map'), {
'param1': 'value1',
'param2': 'value2'
});
// Create a new LatLngBounds object
var markerBounds = new google.maps.LatLngBounds();
// Add your points to the LatLngBounds object.
foreach(marker in markers) {
var point = new google.maps.LatLng(marker.lat, marker.lng);
markerBounds.extend(point);
}
// Then you just call the fitBounds method and the Maps widget does all rest.
map.fitBounds(markerBounds);
Here's your code:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCxuRdCmN2BO5PD7kwI0mO8JflcUOF4CtI&sensor=true">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(50.903033, 10.496063),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var markerBounds = new google.maps.LatLngBounds();
var contentString;
<? php
$i = 1;
foreach($FertigID as $ID) {
$result = mysql_query("SELECT * FROM Daten_CH WHERE ID = ".$ID."");
while ($Ergebnisse = mysql_fetch_array($result)) { // Werden alle ergebnisse (ID´s) in einen Array geschriebenn
if (isset($Ergebnisse["GIS_y"]) && $Ergebnisse["GIS_y"] != "" && $Ergebnisse["GIS_y"] != " ") { ?> contentString = '<input type="button" value="BEARBEITEN"></button>';
var Position = new google.maps.LatLng( <? php echo $Ergebnisse["GIS_y"]; ?> , <? php echo $Ergebnisse["GIS_x"]; ?> );
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker <? php echo $i; ?> = new google.maps.Marker({
position: Position,
map: map,
title: '<?php echo $Ergebnisse["AA_Objektname"]; ?>'
});
markerBounds.extend(Position); // you call this method for each Position (LatLng object)
google.maps.event.addListener(marker <? php echo $i; ?> , 'click', function() {
infowindow.open(map, marker <? php echo $i; ?> );
});
<? php
}
}
$i++;
} ?>
map.fitBounds(markerBounds); // Then you call this method here.
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>

google map markers performance

on my web site http://offersmapper.com/
i have a map that has to show from 2000 to 5000 markers. is really slow.
i tried with markercluster as suggested but nothing... most probably i'm doing something wrong... any one that can help me?:
function initialize() {
var mapOptions = {
zoom: <? echo $zoom; ?>,
center: new google.maps.LatLng(<? echo $lat ?>, <? echo $lng ?>),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var markers_1 = [];
<?
while($deal=mysql_fetch_assoc($query))
{
$t="
var contentString".$deal['id']."='".$info."';
var InfoWin".$deal['id']."= new google.maps.InfoWindow({
content: contentString".$deal['id'].",
maxWidth: 300
});
var marker".$deal['id']." = new google.maps.Marker({
position: new google.maps.LatLng(".$deal['lat'].", ".$deal['lng']."),
icon: ".$icon."
});
google.maps.event.addListener(marker".$deal['id'].", 'click', function() {
InfoWin".$deal['id'].".open(map,marker".$deal['id'].");
});
markers_1.push(marker".$deal['id'].");";
echo $t;
}
?>
var markerCluster_1 = new MarkerClusterer(map, markers_1, {maxZoom: 7, gridSize: 25, styles: styles[0]} );
Try to reduce your html code:
You should pass data to javascript as a json object. Than javascript should iterate over all elements and create markers , etc.. mutch sorter html code, and faster load.
I assume you use jQuery for javascript coding:
... //your code before the while loop
<?
$deals = array();
while($deal=mysql_fetch_assoc($query)){
$deals[$deal[$id]] = $deal;
}?>
<script type="text/javascript">
var deals = <?=json_encode($deals)?>;
var infoWindow = [];
var marker =[];
$.each(deals,function(k,v){
var i = k;
infoWindow[i] = new google.maps.InfoWindow({
content: v.info,
maxWidth: 300 });
markers[i] = new google.maps.Marker({
position: new google.maps.LatLng(v.lat, v.lng), icon: v.icon
});
google.maps.event.addListener(markers[i] , 'click', function(){
infoWindow[i].open(map,markers[i]);
});
});
var markerCluster_1 = new MarkerClusterer(map, markers, {maxZoom: 7, gridSize: 25, styles: styles[0]} );
</script>
And if it is not enough, you can load the data via ajax.