showing json output on google map API v3 - php

I have a json output that shows my info correctly but i am having a hell of a time getting it to show a icon on each pair of lat+lng from my DB
Here is my current code
<?php
require('inc/db.inc.php');
mysql_connect($connect, $user, $pword) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
$sql=mysql_query("SELECT store_lat,store_long FROM location WHERE status='Active'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
$locations=(json_encode($output));
?>
<script src="http://maps.google.com/maps/api/js?sensor=false&key=MY_API_KEY" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var image = 'images/icon.png';
var myLatlng = new google.maps.LatLng(42.548625, -92.548765);
var myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var poiJson = <? echo $locations ?>;
for (var i = 0;i < poiJson.length; i += 1) {
var lat = poiJson[i].store_lat;
var lng = poiJson[i].store_long;
addMarker(lat,lng,i);
};
}
function addMarker(lat,lng,no){
var latlng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
position: latlng,
map: map
// if i uncomment the icon line no map will show at all
//icon: image
});
}
</script>
<? include "header.php"; ?>
<p>
<table width="1024">
<tr>
<td align="center" valign="top"><div id="map_canvas" style="width: 95%; height: 600px;"></div></td>
</tr>
</table>
</p>
</body>
</html>
Edit
if i change the image into the addMarker function this dose not change anything.
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(42.548625, -92.548765);
var myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var poiJson = <? echo $locations ?>;
for (var i = 0;i < poiJson.length; i += 1) {
var lat = poiJson[i].store_lat;
var lng = poiJson[i].store_long;
addMarker(lat,lng,i);
};
}
function addMarker(lat,lng,no){
var image = 'images/icon.png';
var latlng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
position: latlng,
map: map
//icon: image
});
}
</script>

There is no image defined in the scope of addMarker (hence you will get an error). It is only local to initialize. Either define it in addMarker or make it global.

Related

How to pass data from MySQL to Google Maps

I'm confused about how to pass data from PHP to my google maps API.
<script>
<?
$dbFirst = new database;
$dbFirst->query("SELECT getLatitude,getLongitude FROM t_report
WHERE phoneNumber='$idimei' AND tanggal BETWEEN '$tgl1 00:00:00' and '$tgl1 23:59:59' AND (km IS NOT NULL AND km !='') ORDER BY ID ASC LIMIT 1");
$rowFirst=$dbFirst->tampilkan();
while ($rowFirst=$dbFirst->tampilkan()){
$lat=$rowFirst['getLatitude'];
$lon=$rowFirst['getLongtitude'];
}
?>
var marker;
function initMap() {
var mark1 = {lat:X, lng:Y};
var map = new google.maps.Map(document.getElementById('map'), {
center: mark1,
zoom: 18
});
marker = new google.maps.Marker({
position: mark1,
animation: google.maps.Animation.DROP,
map: map
});
marker.addListener('click', toggleBounce);
}
function toggleBounce() {
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
</script>
how do I put $lat and $lon to my mark1 X and Y variable? I'm confused on how to pass data outside PHP.
Thanks for answering
You can use the following method to pass data from PHP variable to JS
Suppose this is where you are querying data from DB and storing it in a variables $lat and $lon
<?php
//data from DB
$lat = "xx.xx";
$lon = "xx.xx";
?>
<script>
// then echo it into the js
// and assign to a js variable
let lat = '<?php echo $lat ;?>';
let lon = '<?php echo $lon ;?>';
// then
function initMap() {
var mark1 = {lat:lat, lng:lon};
var map = new google.maps.Map(document.getElementById('map'), {
center: mark1,
zoom: 18
});
marker = new google.maps.Marker({
position: mark1,
animation: google.maps.Animation.DROP,
map: map
});
marker.addListener('click', toggleBounce);
}
</script>```
To pass variable $lat and $lon from PHP to X and Y in javascript you can do like this:
var marker;
var X ="<?php echo $lat; ?>";
var Y ="<?php echo $lon; ?>";
or more shorter:
var marker;
var X =<?$lat?>;
var Y =<?$lon?>;

Too much recurssion in google map

<script type='text/javascript'>
jQuery(document).ready(function($){
var geocoder;
var map;
var markersArray = [];
var infos = [];
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bounds = new google.maps.LatLngBounds();
var encodedString;
var stringArray = [];
encodedString = document.getElementById("encodedString").value;
stringArray = encodedString.split("****");
var x;
for (x = 0; x < stringArray.length; x = x + 1)
{
var addressDetails = [];
var marker;
addressDetails = stringArray[x].split("&&&");
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
marker = new google.maps.Marker({
map: map,
position: lat,
//Content is what will show up in the info window
content: addressDetails[0]
});
markersArray.push(marker);
google.maps.event.addListener( marker, 'click', function () {
closeInfos();
var info = new google.maps.InfoWindow({content: this.content});
//On click the map will load the info window
info.open(map,this);
infos[0]=info;
});
//Extends the boundaries of the map to include this new location
bounds.extend(lat);
}
//Takes all the lat, longs in the bounds variable and autosizes the map
map.fitBounds(bounds);
//Manages the info windows
function closeInfos(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}
});
</script>
</head>
<body>
<div id='input'>
<?php
$encodedString = "";
$x = 0;
$result = mysql_query("SELECT * FROM `table-name`");
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
if ( $x == 0 )
{
$separator = "";
}
else
{
$separator = "****";
}
$encodedString = $encodedString.$separator.
"<p class='content'><b>Lat:</b> ".$row[1].
"<br><b>Long:</b> ".$row[2].
"<br><b>Name: </b>".$row[3].
"<br><b>Address: </b>".$row[4].
"</p>&&&".$row[1]."&&&".$row[2];
$x = $x + 1;
}
?>
<input type="hidden" id="encodedString" name="encodedString" value="<?php echo $encodedString; ?>" />
</div>
<div id="map_canvas"></div>
I have used above code for google map location from MySQL database.
Above code fetch lat, Lang from MySQL database and dynamically create google map.
When I run above code It gave me error like that:
There are two errors named too much recursion & initMap is not function.
Can anybody help me to sort out it.
Thanks in advance.
You have not defined initMap in your js file. That's why you are getting that error. You probably need to remove the callback part from the google map api script
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
To
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY" async defer></script>
Also check if the lat and lon contain valid numeric values in the following statement
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);

Display multiple locations on Google Map v3 using PHP MYSQL WHILE LOOP

I have this code that was once working but now is not. It is for displaying multiple locations on a map using Google maps version 3, by getting the locations from a table in the database, and looping through them using a PHP WHILE loop. Only one location is being displayed. The code is as below:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map ;
function initialize() {
var latlng = new google.maps.LatLng(53.933056, 9.503611);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?
$query = mysql_query("SELECT
markers.id,
markers.place,
markers.address,
markers.lat,
markers.lng,
markers.description,
markers.type,
images.id,
images.thumb_path,
images.main
FROM
markers,images
WHERE
markers.type = '".$type."'
AND markers.id = images.id
AND images.main = 1
");
$numRows = mysql_num_rows($query);
if($numRows > 0){
while($row = mysql_fetch_assoc($query)){
?>
var contentString = '<div id="content">'+
'<img src="<?=$row['thumb_path'];?>" width="100" height="100" hspace="2" align="left" />'+
'<h4><?=$row['place'];?></h4><p><?=$row['address'];?></p>'+
'<p align="right">More Details'+
'</div>';
var marker = add_marker(<?=$row['lat'];?>, <?=$row['lng'];?>,"<?=strtoupper($row['place']);?>",contentString);
marker.setMap(map);
<? } ?>
<? } ?>
}
function add_marker(lat,lng,title,box_html) {
var infowindow = new google.maps.InfoWindow({
content: box_html
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
title: title
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
return marker;
}
Kindly assist.

passing variables into google maps and refresh

WORK FINE YET
I need to show only the items entered username and password.
I can not send php variables to javascript to call back to the database and update the map
I have this code work fine ( only part):
function initialize() {
var myOptions = {
zoom: 10,
//center: new google.maps.LatLng(-33.9, 151.2),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
<?
$query = mysql_query("SELECT lat2,lon2,idruta,FROM_UNIXTIME(time) as time FROM bus");
$valores="[";
$indice = 0;
while ($row = mysql_fetch_array($query)){
$namex=$row['idruta'];
$lat=$row['lat2'];
$lon=$row['lon2'];
$desc = $row['time'];
$name = $namex ." ".$desc;
$indice++;
$valores = $valores. "['$name',$lat,$lon,$indice],";
}
$valores = substr($valores, 0, -1);
$valores = $valores ."]";
echo ("setMarkers(map, $valores)");
?>
// setMarkers(map, beaches);
}
function codeAddress() {
var myOptions = {
zoom: 10,
//center: new google.maps.LatLng(-33.9, 151.2),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
<?
$query = mysql_query("SELECT lat2,lon2,idruta,FROM_UNIXTIME(time) as time FROM bus where user = $user");
$valores="[";
$indice = 0;
while ($row = mysql_fetch_array($query)){
$namex=$row['idruta'];
$lat=$row['lat2'];
$lon=$row['lon2'];
$desc = $row['time'];
$name = $namex ." ".$desc;
$indice++;
$valores = $valores. "['$name',$lat,$lon,$indice],";
}
$valores = substr($valores, 0, -1);
$valores = $valores ."]";
echo ("setMarkers(map, $valores)");
?>
}
function setMarkers(map, locations) {
var image = new google.maps.MarkerImage('marker-panel.png',
new google.maps.Size(220, 39),
new google.maps.Point(0,0),
new google.maps.Point(50, 39));
/* var shadow = new google.maps.MarkerImage('marker-panel.png',
new google.maps.Size(37, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));*/
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
//shadow: shadow,
icon: image,
shape: shape,
title: beach[0],
zIndex: beach[3]
});
bounds.extend(myLatLng);
var label = new Label({
map: map
});
label.set('zIndex', 1234);
label.bindTo('position', marker, 'position');
label.set('text', beach[0]);
//label.bindTo('text', marker, 'position');
}
map.fitBounds(bounds);
}
</script>
</head>
<body onload="initialize()">
<div>
<input id="usuario" type="textbox" value="usuario">
<input id="password" type="password" value="password">
<input type="button" value="Enviar" onclick="codeAddress()">
</div>
<div id="map_canvas" style="height:90%;top:30px"></div>
</body>
</html>
but I need to show only the user points and password entered. And i donĀ“t know
thanks
Before calling those java script function write one php code to check userpoints and password.If userpoints and password is correct means only those scripts are called.

Google Map marker window

I'm trying to add a link in my Google Map marker window. But my code only shows the marker and the window but it does not show the link.
I'm trying to add the link in this line:
$marker['infowindow_content'] = "<?php echo anchor('index/get_by_id/$id',{$row->subject} on {$row->address}')?>";
when the link is clicked it go to some function of my index controller.
but why the link is not appearing in the window.
controller:
function index()
{
if(empty($_POST)){
$this->load->helper('form');
$this->googlemaps->initialize();
$marker = array();
//$this->main_model->get_map();
if($result = $this->main_model->ll()){
//var_dump($result);
foreach($result->result() as $row) {
//var_dump($row);
//$data[]=$row;
$marker['position'] = "{$row->lat},{$row->lng}";
$id=$row->id;
$marker['infowindow_content'] = "<?php echo anchor('index/get_by_id/$id',{$row->subject} on {$row->address}')?>";
$marker['animation'] = 'DROP';
//var_dump($marker['position ']);
$this->googlemaps->add_marker($marker);
}
}
//$this->googlemaps->add_marker($marker);
$data['map'] = $this->googlemaps->create_map();
$data['list'] = $this->main_model->getdata();
$this->load->view('main_view',$data);
}
}
Model:
public function ll($id = '')
{
$sql = $this->db->get('info');
if ($sql->num_rows () >0) {
return $sql;
}
else{
return null;
}
}
The generated html from my code(the map part only):
<script type="text/javascript">
//<![CDATA[
var map; // Global declaration of the map
var iw = new google.maps.InfoWindow(); // Global declaration of the infowindow
var lat_longs = new Array();
var markers = new Array();
function initialize() {
var myLatlng = new google.maps.LatLng(65.84815, 24.14670);
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var myLatlng = new google.maps.LatLng(65.85051,24.14529);
var markerOptions = {
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP
};
marker_0 = createMarker(markerOptions);
marker_0.set("content", "<?php echo anchor('index/get_by_id/1',street problem on something home)?>");
google.maps.event.addListener(marker_0, "click", function() {
iw.setContent(this.get("content"));
iw.open(map, this);
});
var myLatlng = new google.maps.LatLng(65.84931,24.14555);
var markerOptions = {
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP
};
marker_1 = createMarker(markerOptions);
marker_1.set("content", "<?php echo anchor('index/get_by_id/2',hello on 11 some)?>");
google.maps.event.addListener(marker_1, "click", function() {
iw.setContent(this.get("content"));
iw.open(map, this);
});
var myLatlng = new google.maps.LatLng(65.84858,24.14160);
var markerOptions = {
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP
};
marker_2 = createMarker(markerOptions);
marker_2.set("content", "<?php echo anchor('index/get_by_id/3',problem street on 78900 street)?>");
google.maps.event.addListener(marker_2, "click", function() {
iw.setContent(this.get("content"));
iw.open(map, this);
});
var myLatlng = new google.maps.LatLng(65.85000,24.14773);
var markerOptions = {
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP
};
marker_3 = createMarker(markerOptions);
marker_3.set("content", "<?php echo anchor('index/get_by_id/4',gulshan street on 11 gulshan)?>");
google.maps.event.addListener(marker_3, "click", function() {
iw.setContent(this.get("content"));
iw.open(map, this);
});
var myLatlng = new google.maps.LatLng(65.84620,24.14593);
var markerOptions = {
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP
};
marker_4 = createMarker(markerOptions);
marker_4.set("content", "<?php echo anchor('index/get_by_id/5',broken road on banani)?>");
google.maps.event.addListener(marker_4, "click", function() {
iw.setContent(this.get("content"));
iw.open(map, this);
});
var myLatlng = new google.maps.LatLng(65.84961,24.15164);
var markerOptions = {
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP
};
marker_5 = createMarker(markerOptions);
marker_5.set("content", "<?php echo anchor('index/get_by_id/6',no lamp on arbritary)?>");
google.maps.event.addListener(marker_5, "click", function() {
iw.setContent(this.get("content"));
iw.open(map, this);
});
}
function createMarker(markerOptions) {
var marker = new google.maps.Marker(markerOptions);
markers.push(marker);
lat_longs.push(marker.getPosition());
return marker;
}
window.onload = initialize;
//]]>
The issue is with this line:
$marker['infowindow_content'] = "<?php echo anchor('index/get_by_id/$id',{$row->subject} on {$row->address}')?>";
The content for an InfoWindow is a string containing the actual HTML code. In your case, the <?php block is ignored as you can see in the generated HTML:
marker_0.set("content", "<?php echo anchor('index/get_by_id/1',street problem on something home)?>");
It has to be :
marker_0.set("content", "<a href='index/get_by_id/1'>street problem on something home</a>");
Try this:
<?php
$subject = $row->subject;
$address = $row_>address;
?>
var index = '<?php echo $id; ?>';
var subject = '<?php echo $subject; ?>';
var address = '<?php echo $address; ?>';
$marker['infowindow_content'] = "<a href='index/get_by_id/" + index + "'>" + subject + " on " + address + "</a>";

Categories