How to insert google maps through a while loop? - javascript

I want to insert a google map in a div(html) which generates through a while loop. Google map gets coordinates from the database.
It should appear as in this image
Since I need to use a google map api key, I used following code.
But, It shows a map, only in the first div, using the last coordinates of the database, and doesn't show any other map in any other divs.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function currentUsers($connection){
$sql = "SELECT * FROM user ";
$result = mysqli_query($connection, $sql);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)) {
$userID = $row['id'];
$firstName = $row['firstname'];
$country = $row['country'];
$latitude = $row['latitude'];
$longitude = $row['longitude'];
echo '<div>
<div align = "left">
<h3>'. $userID. " ". $firstName. " ". $country. '</h3>
</div>
<div id = "map" align = "right">
<script> <!--Google map api-->
function initMap() {
var x = '. $latitude. ';
var y = '. $longitude. ';
var myLatLng = {lat: x, lng: y};
var map = new google.maps.Map(document.getElementById(\'map\'), {
center: myLatLng,
scrollwheel: true,
zoom: 4
});
var marker = new google.maps.Marker({
map: map,
position: myLatLng,
title: \'Hello World!\'
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
</div>
</div>';
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
currentUsers($connection);
?>
<html>
<head><title></title>
<style> #map {width: 500px; height: 400px; } </style> <!--Size of the map-->
</head>
<body></body>
</html>

ID of each div should be unique. Try this
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function currentUsers($connection){
$sql = "SELECT * FROM user ";
$result = mysqli_query($connection, $sql);
$x= 0;
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)) {
$userID = $row['id'];
$firstName = $row['firstname'];
$country = $row['country'];
$latitude = $row['latitude'];
$longitude = $row['longitude'];
echo '<div>
<div align = "left">
<h3>'. $userID. " ". $firstName. " ". $country. '</h3>
</div>
<div id = "map_'.$x.'" align = "right">
<script> <!--Google map api-->
function initMap() {
var x = '. $latitude. ';
var y = '. $longitude. ';
var myLatLng = {lat: x, lng: y};
var map = new google.maps.Map(document.getElementById("map_'.$x.'"), {
center: myLatLng,
scrollwheel: true,
zoom: 4
});
var marker = new google.maps.Marker({
map: map,
position: myLatLng,
title: \'Hello World!\'
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
</div>
</div>';
$x++;
}
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
currentUsers($connection);
?>
<html>
<head><title></title>
<style> #map {width: 500px; height: 400px; } </style> <!--Size of the map-->
</head>
<body></body>
</html>

You can only reliably include the API once. Currently you are including the API for each map you add.
You can also only have one function with the name initMap, currently you are including multiple versions of that function.
You can only have one div with id="map", currently you have one for each location.
related question (javascript only, no PHP): Adding multiple map canvases to window - Google Maps Javascript API v3

This is 100% working for me i've tested this code
<?php
$arr='';
$connection = mysqli_connect('localhost', 'root', '', 'users');
function currentUsers($connection){
$sql = "SELECT * FROM user";
$result = mysqli_query($connection, $sql);
$x= 0;
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)) {
$userID = $row['id'];
$firstName = $row['firstname'];
$country = $row['country'];
$arr[] = array($row['latitude'],$row['longitude'],$x);
echo '<div style="width:100%;">
<div style="width:250px; height: 150px; float :left;">
<h3>'. $userID. ". ". $firstName. " ". $country. '</h3>
</div>
<div id = "map_'.$x.'" style="width:250px;height: 150px;"> </div>
</div>';
$x++;
}
echo '<script> var mymaps ='.json_encode($arr).'</script>';
}else{
echo "Currently there are no users!";
}
mysqli_close($connection);
}
currentUsers($connection);
?>
<script type="text/javascript" src="http://maps.google.com/maps/api/js"></script>
<script>
var maps = [];
function initialize(id, myLatLng) {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 9,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
maps[id] = new google.maps.Map(document.getElementById('map_'+id),
mapOptions);
var marker = new google.maps.Marker({
map: maps[id],
position: myLatLng,
title: 'Hello World!'
});
}
$(document).ready(function(){
for( var i = 0; i < mymaps.length; i++)
{
var x = parseFloat(mymaps[i][0]);
var y = parseFloat(mymaps[i][1]);
var myLatLng = {lat: x, lng: y};
google.maps.event.addDomListener(window, 'load', initialize(mymaps[i][2],myLatLng)); // two calls
}
});
</script>

Related

Only load 10 markers from database

I have a question. I make a project using google maps. i put 30 data on database. but when i wanna show the marker on the map, it only load for 10 data. also when I filter my data based on the category, it load for 10 data only. I check inspact element on my browser (im using mozilla) and found this error : "SyntaxError: unterminated string literal" what does it means?
Here's my code to show markers & map on the web :
<?php
$title = "Peta Masjid";
include_once "header.php";
?>
<div class="row">
<div class="col-md-12">
<div class="panel panel-info panel-dashboard centered">
<div class="panel-heading">
<h2 class="panel-title"><strong> <?php echo $title ?> </strong></h2>
</div>
<div class="panel-body">
<div id="map" style="width:100%;height:380px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyAbXF62gVyhJOVkRiTHcVp_BkjPYDQfH5w">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(-6.966667, 110.416664),
disableDefaultUI: true
};
var mapElement = document.getElementById('map');
var map = new google.maps.Map(mapElement, mapOptions);
setMarkers(map, officeLocations);
}
var officeLocations = [
<?php
$data = file_get_contents('http://localhost:8082/sig/getdata.php');
$no=1;
if(json_decode($data,true)){
$obj = json_decode($data);
foreach($obj->results as $item){
?>
['<?php echo $item->id_masjid ?>','<?php echo $item->nama_masjid ?>','<?php echo $item->alamat ?>', '<?php echo $item->longitude ?>', '<?php echo $item->latitude ?>','<?php echo $item->gambar ?>'],
<?php
}
}
?>
];
function setMarkers(map, locations)
{
var globalPin = 'img/tanda.png';
for (var i = 0; i < locations.length; i++) {
var office = locations[i];
var myLatLng = new google.maps.LatLng(office[4], office[3]);
var infowindow = new google.maps.InfoWindow({content: contentString});
var contentString =
'<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h5 id="firstHeading" class="firstHeading">'+ office[1] + '</h5>'+
'<div id="bodyContent">'+
'<p>' + office[2] + '</p>' +
'<p><img src="img/'+office[5]+'" style="width:50%;height:190px;" /></p>' +
'<p><a href=detail.php?id='+office[0]+'>Info Detail</p></a>'+
'</div>'+
'</div>';
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: office[1],
icon:'img/tanda.png'
});
google.maps.event.addListener(marker, 'click', getInfoCallback(map, contentString));
}
}
function getInfoCallback(map, content) {
var infowindow = new google.maps.InfoWindow({content: content});
return function() {
infowindow.setContent(content);
infowindow.open(map, this);
};
}
initialize();
</script>
</div>
</div></div></div>
</div>
</div>
<?php include_once "footer.php"; ?>
And here's code to get data from database (getdata.php)
<?php
include "connection.php";
$Q = mysql_query("SELECT * FROM mosques WHERE category = 'Mushola'")or die(mysql_error());
if($Q){
$posts = array();
if(mysql_num_rows($Q))
{
while($post = mysql_fetch_assoc($Q)){
$posts[] = $post;
}
}
$data = json_encode(array('results'=>$posts));
echo $data;
}
?>
You can use a counter in your while loop that counts to ten and then breaks the loop or an if statement than only runs if the counter is not 10
-Aron DC

How to show multiple Location on google map using php and mysql database

I have the following code, it works fine but picks only one location,
I have multiple location against 'cid' and I want to get and display all the location.
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<?php
$sql = "select * from locator_areas where cid=$city";
$res = mysql_query($sql);
while($row=mysql_fetch_assoc($res)){
?>
<script> var myLatLng = {lat: <?php echo $row['latitude'] ?>, lng: <?php echo $row['longitude']?>};</script>
<?php } ?>
<script>
function initMap() {
icon='img/bk-loc.png';
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon:icon,
title: "<?php echo $long.' || '. $lat?> "
});
}
</script>
<script async defer
src="http://maps.googleapis.com/maps/api/js?key=myKEY&callback=initMap">
</script>
<script> initMap();</script>
</body>
You can add multiple markers by adding new google.Maps.Marker() multiple times. It would make sense to iterate over a array to do this.
The code should look like this
<?php
require("phpsqlsearch_dbinfo.php");
// Get parameters from URL
$center_lat = $_GET["lat"];
$center_lng = $_GET["lng"];
$radius = $_GET["radius"];
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
/ Opens a connection to a mySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Search the rows in the markers table
$query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
mysql_real_escape_string($center_lat),
mysql_real_escape_string($center_lng),
mysql_real_escape_string($center_lat),
mysql_real_escape_string($radius));
$result = mysql_query($query);
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
?>
Check out these links https://developers.google.com/maps/articles/phpsqlsearch_v3
https://developers.google.com/maps/articles/phpsqlajax_v3
You can add multiple markers by adding multiple times using for loop. It would make sense to iterate over a array to do this.
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<?php
$sql = "select * from locator_areas where cid=$city";
$res = mysql_query($sql);
while($row=mysql_fetch_assoc($res)){
$i=0;
?>
<script> var myLatLng = new Array();
myLatLng[<?php echo $i; ?>] = "<?php echo $value['latitude']; ?> , <?php echo $value['longitude']; ?>"; </script>
<?php
$i++;
} ?>
<script>
var locations = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < pins.length; i++) {
var coordinates = pins[i].split(", ");
locations[i] = new google.maps.LatLng(coordinates[0], coordinates[1]);
latlngbounds.extend(locations[i]);
}
var mapOptions = {
zoom: 9,
disableDefaultUI: true,
center: myLatlng,
draggable: false,
scrollwheel: false,
disableDoubleClickZoom: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
//var contentString = "<p>I am HTML</p>";
var image = 'img/bk-loc.png';
var markers = [];
for (var i = 0; i < locations.length; i++){
markers[i] = new google.maps.Marker({
position: locations[i],
map: map,
title: pin_quick_data[i],
icon: image
});
}
</script>
<script async defer
src="http://maps.googleapis.com/maps/api/js?key=myKEY&callback=initMap">
</script>
<script> initMap();</script>
</body>
You are saving N positions in one variable. In that variable only the last position is saved. If you want to save N positions in memory you have to use an array.
To ship PHP variables to Javascript I recomend to use PHP and the PHP function json_encode.
In the end of your example, you are calling initMap. It is not needed since this function is called from your googleapis script include.
Rewritten code should look like this:
<body>
<div id="map"></div>
<?php
$sql = "select * from locator_areas where cid=$city";
$res = mysql_query($sql);
$positions = array();
while($row=mysql_fetch_assoc($res)){
/* <script> var myLatLng = {lat: <?php echo $row['latitude'] ?>, lng: <?php echo $row['longitude']?>};</script>*/
$positions[] = array(
'lat' => $row['latitude'],
'lng' => $row['longitude'],
'title' => $row['longitude']. ' || ' .$row['latitude']
);
}
?>
<script>
var positions = <?php echo json_encode($positions) ?>;
</script>
<script>
function initMap() {
icon='img/bk-loc.png';
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
positions.forEach(function(position){
var marker = new google.maps.Marker({
position: {
'lat' : position.lat,
'lng' : position.lng
},
map: map,
icon:icon,
title: position.title
});
});
}
</script>
<script async defer src="http://maps.googleapis.com/maps/api/js?key=myKEY&callback=initMap">
</script>
</body>

How to change the circle color in google maps api dynamically?

I am new to this forum and currently working with Google maps API for tracking and monitoring purposes. I want to change the color of circle dynamically and the data's are currently stored in a data base. But the problem is i am getting the same color (black) for all the circles. I can't find where i went wrong. Please help me. Below are the code snippets.
<?php
$latvalue = array();
$longvalue = array();
$population= array();
$color= array();
$servername = "localhost";
$username = "test";
$password = "xxxxxx";
$dbname = "test_db";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM mytable";
$result = mysqli_query($conn, $sql);
$number =mysqli_num_rows($result);
$index = 0;
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$yourArray[$index] = $row;
// echo "id: " . $row["id"]. " - lat: " . $row["latitude"]. "- log: " . $row["longitude"]. "<br>";
$index++;
}
}
else {
echo "0 results";
}
mysqli_close($conn);
for($x=0;$x<$number;$x++)
{
$latvalue[$x] = $yourArray[$x]['latitude'];
$longvalue[$x] = $yourArray[$x]['longitude'];
$population[$x] = $yourArray[$x]['size'];
$color[$x] = $yourArray[$x]['color'];
}
//echo $latvalue[0];
?>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Circles</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// This example creates circles on the map, representing populations in North
// America.
// First, create an object containing LatLng and population for each city.
naming = new Array();
<?php
$test_str = "var citymap = {";
for($i = 0; $i < $number; $i++){
$test_str .= $i+1 . ": {center: {lat:" .$latvalue[$i]. ",lng:" . $longvalue[$i] . "}, population: " . $population[$i] . ", color: '". $color[$i] ."'},";
}
$test_str .= "};" ;
echo $test_str;
?>
function initMap() {
// Create the map.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: {lat: 11.0773756, lng: 76.98866040000007},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
// Construct the circle for each value in citymap.
// Note: We scale the area of the circle based on the population.
for (var city in citymap) {
// Add the circle for this city to the map.
var cityCircle = new google.maps.Circle({
strokeColor: '#FFFFFF',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: 'citymap[city].color',
fillOpacity: 0.7,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].population) * 1
});
}
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAZMU3v1pUYZuf8Bbiv6YQi5N3IY7pTQxc&callback=initMap">
</script>
</body>
</html>
This is my page : http://mybbb.esy.es/xmltest.php
View this so that you can find where the problem exists.
The color values are stored like this in a database table : #B22122
you can set circle stoke color and fill color like that.
circle.setOptions({
fillColor: '#F5F5F5',
strokeColor: '#528BE2'
});
You need to put inside event.
here is full code circle will change when mouse is over.
google.maps.event.addListener(circle, 'mouseover', function () {
console.log('la la la');
circle.setOptions({
fillColor: '#F5F5F5',
strokeColor: '#528BE2'
});
});
you can use setOptions
cityCircle.setOption( strokeColor: '#00FF00');

Plotting multiple markers on google map

i have a php file that output this json data
[{"lat":"5.92687670","lng":"116.10072270"},{"lat":"6.23331022","lng":"116.42924500"},{"lat":"47.62456131","lng":"-122.35644531"},{"lat":"47.60636520","lng":"-122.33765411"},{"lat":"47.61282349","lng":"-122.34567261"},{"lat":"47.60596085","lng":"-122.34036255"},{"lat":"47.61397552","lng":"-122.34546661"},{"lat":"47.61721420","lng":"-122.32658386"}]
this is the php code for the result above (genjson.php) :
<?php
require("connect.php");
$link = mysqli_connect("localhost", "$username", "$password", "$database");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
mysqli_select_db($link,"senangbah");
$var = array();
$sql = "SELECT `lat`, `lng` FROM markers";
$result = mysqli_query($link, $sql);
while($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
header('Content-Type: application/json');
echo json_encode($var);
?>
and this is the javascript for the map
function initMap() {
var latlng = new google.maps.LatLng(5.5117338, 117.0463637);
var myOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById("map"),myOptions);
$.getJSON('genjson.php', function(markers) {
for (i = 0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i][0], markers[i][1]),
map: map
});
}
});
}
map load fine, but no markers are shown? which part am i doing wrong? tq
The error is in this statement:
position: new google.maps.LatLng(markers[i][0], markers[i][1]),
Since each marker[n] is an object, not an array, you must instead use:
position: new google.maps.LatLng(markers[i].lat, markers[i].lng),
BTW note that you'd better to write var marker = ... rather than merely marker = ... to avoid polluting global space.

Google Maps Marker Content in box

I get the Coordinates and the Names and "ID" out of an MySQL Table but why is in every Marker the same Text an also the same link ?
Why is the text not different ???
It show only the last ID but it should add after every element in the data base an other marker !
The markers are at the right Position and the "Content" is in the Source Code also right but not at the markes why ?!
Please Help
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(51.124213, 10.60936),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new
google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
var contentString;
var elementeInArray = 0;
var LatLngList = new Array;
<? php
$i = 1;
foreach($FertigID as $ID) {
$result = mysql_query("SELECT * FROM Daten_CH WHERE Objektnummer = ".$ID.
"");
while ($Ergebnisse = mysql_fetch_array($result)) {
// Werden alle ergebnisse (ID´s) in einen Array geschriebenn
echo $$Ergebnisse["Objektnummer"];
if (isset($Ergebnisse["Gis_y"]) && $Ergebnisse["Gis_y"] != "" &&
$Ergebnisse["Gis_y"] != " ") {
echo $i; ?>
// MARKER TEXT
contentString = '<?php echo $i; ?> </br><?php echo
$Ergebnisse["Objektname"]; ?>
</br><a href="Change.php?ID=<?php echo $ID; ?>">
<input type="button" value="BEARBEITEN"></button></a>';
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; ?> );
});
LatLngList[elementeInArray] = new google.maps.LatLng( <? php echo $Ergebnisse["Gis_y"]; ?> , <? php echo $Ergebnisse["Gis_x"]; ?> );
elementeInArray++;
<? php
}
}
$i++;
}
?>
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
// Go through each...
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
// And increase the bounds to take this point
bounds.extend(LatLngList[i]);
}
// Fit these bounds to the map
map.fitBounds(bounds);
var opt = {
minZoom: 1,
maxZoom: 12
};
map.setOptions(opt);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Because you should assign the contentString to the marker, and update the infowindow with each markers assigned content instead. As it is now, the only contentString available is the last created. Furthermore, you really dont have to create multiple numbered markers. You just need one marker reference only.
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
position: Position,
map: map,
content: contenString, // <-- assign content to the marker itself
title: '<?php echo $Ergebnisse["AA_Objektname"]; ?>'
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(this.content);
infowindow.open(map, this);
});
This would do the trick.

Categories

Resources