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.
Related
I wrote the code below... this code is to select to long and lati already inserted in database and create a marker in the google map, I tried to put the selected data in a table, it worked fine, but once I put them on the map as marker, it show me only on marker, can anyone help please?
<?php
$conn = getConn();
$sql ="select Latitude,Longtitude from location";
$result=$conn->query($sql);
while($row = mysqli_fetch_array($result)){
$locations = array(
$row['Latitude'],
$row['Longtitude']
);
foreach ($locations as $loc){
// echo $loc . "</br>";
$Latitude = $row['Latitude'];
$Longtitude = $row['Longtitude'];
echo $Latitude . "</br>" . $Longtitude;
}
}
?>
<script>
function initMap(){
var location = {lat: <?=$Latitude?>, lng: <?=$Longtitude?>};
var map= new google.maps.Map(document.getElementById("map"),{
zoom: 13,
center: location});
var marker = new google.maps.Marker({position:location, map:map});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyByZSFwCa5FByzySCLUPzLqzeWKt3RyNwA&callback=initMap">
</script>
You'll need to create an instance of marker for every one you want to appear on the map.
The location variable only holds the last one; you'll have to do something like:
var location = {lat: <?=$Latitude?>, lng: <?=$Longtitude?>};
var map = new google.maps.Map(document.getElementById("map"),{
zoom: 13,
center: location});
for (let loc of <?=$locations?>) {
new google.maps.Marker({position:loc, map:map});
}
I have created a map to pin point the exact location for the customer's provided address. I am getting lat long for the address but it is not pointing out with a map marker on the map I do not know why it is not pointing out can anyone help me out pleasen here is my code
<?php
$addresse = $_POST['address'];
$prepAddr = str_replace(' ','+',$addresse);
$geocode = file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output = json_decode($geocode);
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
?>
<div id="map" style="width:400px;height:400px;"></div>
<script>
function unick() {
var mapOptions = {
center: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>),
zoom: 10,
mapTypeId: google.maps.MapTypeId.satellite
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
}
</script>
You have to add a marker to the map, like this:
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var latLng = new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: 'You are here'
label: 'You are here'
});
Edit: added title and label properties. For more information, see the Google Maps API Reference
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>
i have a code that is supposed to fetch data (latitude and longitude) from database and display it on google map along with markers, the problem is that it fetches and displays latitude and longitude of only one row, but it is supposed to show all the places. Would appreciate if anyone could help me.
<script>
<?php
require 'connection.php';
$parent_id = $_GET['country'];
$fid = $_GET['fid'];
$sql = "SELECT * FROM features_for_office WHERE parent_id='".$parent_id."' and fid='".$fid."' ";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$officeid= $row["officeid"];
$sql1 = "SELECT * FROM register_office WHERE id='".$officeid."' ";
$result1 = mysqli_query($con, $sql1);
if (mysqli_num_rows($result1) > 0)
{
while($row1 = mysqli_fetch_assoc($result1))
{
$officelat= $row1["lat"];
$officelon= $row1["lon"];
$officetitle= $row1["officetitle"];
//echo $officelat;
//echo $officelon;
//echo $officetitle;
?>
var myCenter=new google.maps.LatLng(<?php echo $officelat;?>,<?php echo $officelon;?>);
function initialize()
{
var mapProp = {
center:myCenter,
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content:"<?php echo $officetitle;?>"
});
infowindow.open(map,marker);}
google.maps.event.addDomListener(window, 'load', initialize);
<?}
}
}
}
mysqli_close($con);
?>
</script>
<div id="googleMap" style="width:1145px;height:380px;"></div>
The error is that you are initializing the map every time until the loop completes,it will recreate the map every time and the last latlon marker will be shown on the map.Call the initialize method on page load and place the following code inside the loop.
var myCenter=new google.maps.LatLng(<?php echo $officelat;?>,<?php echo $officelon;?>);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
using SQL you can fetch Latitude and Longitude from Database using this code:
protected void googleMap_Load(object sender, EventArgs e)
{
//Establishing SQL connection
SqlConnection connStr = new
SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
connStr.Open();//Open the connection to Database
//Generate the database query to fetch the content details
SqlCommand cmd = new SqlCommand("select LAT,LON from DATA where ID=9", connStr);
SqlDataAdapter sqlda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sqlda.Fill(ds);
}
The Problem still remains as how to use this dataTable to set marker on google map...
The problem can be re-framed as to fetch the LatLng from database
I used the script to display map
<script>
var myLatLon = new google.maps.LatLng(13, 77);//Defining Latitude and Longitude
var mapProp = {
center: myLatLon, // Center of display page.
zoom: 8, //Zoom level
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('dvMap'), mapProp);
var marker = new google.maps.Marker({
position: myLatLon,
map: map,
});
</script>
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.