I have a PHP code giving back an array
<?php
$sql5 = "SELECT * FROM Building";
$result5 = $connect->query($sql5);
$emparray = array();
while($row5 = $result5->fetch(PDO::FETCH_ASSOC)) {
$coordLat = floatval($row5['Building_lat']);
$coordLng = floatval($row5['Building_lng']);
$emparray[] = array( $row5['Building_name'] , $coordLat , $coordLng , $row5['Building_period'] );
}
$jsonstring= json_encode($emparray);
?>
output from $jsonstring is
[["Hotel Montgomery",50.85000000000000142108547152020037174224853515625,4.339999999999999857891452847979962825775146484375,"June"]]
I need to use these array to put markers on a Google Map.
That's where JavaScript enter the game.
markers1 = <?php echo $jsonstring; ?>;
function initialize() {
var center = new google.maps.LatLng(50.85,4.34);
var mapOptions = {
zoom: 13,
center: center,
disableDefaultUI: true,
styles: noPoi
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
for (i = 0; i < markers1.length; i++) {
addMarker(markers1[i]);
}
}
function addMarker(marker) {
var category = marker[4];
var title = marker[1];
var pos = new google.maps.LatLng(marker[2], marker[3]);
var content = marker[1];
marker1 = new google.maps.Marker({
title: title,
position: pos,
category: category,
map: map
});
gmarkers1.push(marker1);
google.maps.event.addListener(marker1, 'click', (function (marker1, content) {
return function () {
console.log('Gmarker 1 gets pushed');
infowindow.setContent(content);
infowindow.open(map, marker1);
map.panTo(this.getPosition());
map.setZoom(15);
}
})(marker1, content));
}
Problem is, I need to add a space after the comma of each array in order to make it work. Otherwise, the coordinates doesn't work.
If I write it manually (without the echo, adding space), it's working. Of course these array come from an SQL query and I need an echo to get all datas.
If I get it right, what you need is join your array, transform into a string with a particular pattern. Try echo join(", ", $emparray); if matches your case then just use this return in a variable instead of your $jsonstring.
I am trying to get markers dynamically from the database using sql and php. The problem that i am facing is making the marker array in javascript. I have already referred the questions asked on stackoverflow but no luck...
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
initMap(latitude,longitude);
addMarker(latitude,longitude);
}
function initMap(latitude,longitude){
var options = {center :{lat:latitude, lng :longitude} ,
zoom:8
}
var map = new google.maps.Map(document.getElementById('map'),options);
var marker = new google.maps.Marker({
position:{lat:latitude, lng :longitude},
map:map
})
}
var markers = [
<?php
require_once '../includes/dbconfig.inc.php';
$marker_fetcher = "SELECT ad_lat,ad_long FROM `tbl_ads`";
$result = mysqli_query($conn,$marker_fetcher);
while ($row = mysqli_fetch_assoc($result)) {
$lat = $row['ad_lat'];
$long = $row['ad_long'];
echo '{';
echo $lat;
echo ',';
echo $long;
echo '},';
}
?>
];
function addMarker(props){
alert(markers.length)
}
$(document).ready(function(){
getLocation();
});
javascript from source
{19.1643153,72.98971789999996},{19.1816553,72.9711542},{19.2403305,73.13053949999994},{29.6856929,76.99048249999998},{19.2532887,73.13668610000002},{19.2532887,73.13668610000002},{19.2292364,72.85967119999998},{19.2292364,72.85967119999998},{19.0606917,72.83624970000005},{18.5596581,73.7799374},{19.157935,72.99347620000003},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{30.900965,75.85727580000002},{19.2403305,73.13053949999994},{19.157935,72.99347620000003},{19.157935,72.99347620000003},{19.157935,72.99347620000003},{19.157935,72.99347620000003},{53.9332706,-116.5765035},{19.157935,72.99347620000003},{19.2183307,72.97808970000006},{19.157935,72.99347620000003},{53.9332706,-116.5765035},{46.227638,2.213749000000007},{19.157935,72.99347620000003},{19.157935,72.99347620000003},
The array of marker positions is not a valid javascript array. Make the positions to be google.maps.LatLngLiteral objects. Change the code that generates the javascript for your markers array from:
var markers = [
<?php
require_once '../includes/dbconfig.inc.php';
$marker_fetcher = "SELECT ad_lat,ad_long FROM `tbl_ads`";
$result = mysqli_query($conn,$marker_fetcher);
while ($row = mysqli_fetch_assoc($result)) {
$lat = $row['ad_lat'];
$long = $row['ad_long'];
echo '{';
echo $lat;
echo ',';
echo $long;
echo '},';
}
?>
];
To:
var markers = [
<?php
require_once '../includes/dbconfig.inc.php';
$marker_fetcher = "SELECT ad_lat,ad_long FROM `tbl_ads`";
$result = mysqli_query($conn,$marker_fetcher);
while ($row = mysqli_fetch_assoc($result)) {
$lat = $row['ad_lat'];
$long = $row['ad_long'];
echo '{lat:';
echo $lat;
echo ', lng:';
echo $long;
echo '},';
}
?>
];
So your markers array looks like this:
var markers = [
{lat: 19.1643153, lng: 72.98971789999996},
{lat: 19.1816553, lng: 72.9711542},
{lat: 19.2403305, lng: 73.13053949999994},
// ...
];
proof of concept fiddle
code snippet:
var bounds;
var map = null;
function initMap(latitude, longitude) {
var options = {
center: {
lat: latitude,
lng: longitude
},
zoom: 8
}
map = new google.maps.Map(document.getElementById('map'), options);
var marker = new google.maps.Marker({
position: {
lat: latitude,
lng: longitude
},
map: map
})
bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
addMarker(markers[i]);
}
map.fitBounds(bounds);
}
var markers = [{lat:19.1643153, lng:72.98971789999996}, {lat:19.1816553, lng:72.9711542}, {lat:19.2403305, lng:73.13053949999994}, {lat:29.6856929, lng:76.99048249999998}, {lat:19.2532887, lng:73.13668610000002}, {lat:19.2532887, lng:73.13668610000002}, {lat:19.2292364, lng:72.85967119999998}, {lat:19.2292364, lng:72.85967119999998}, {lat:19.0606917, lng:72.83624970000005}, {lat:18.5596581, lng:73.7799374}, {lat:19.157935, lng:72.99347620000003}, {lat:30.900965, lng:75.85727580000002}, {lat:19.2403305, lng:73.13053949999994}, {lat:19.157935, lng:72.99347620000003}, {lat:53.9332706, lng:-116.5765035}, {lat:19.157935, lng:72.99347620000003}, {lat:19.2183307, lng:72.97808970000006}, {lat:46.227638, lng:2.213749000000007}];
function addMarker(props) {
console.log(JSON.stringify(props));
var marker = new google.maps.Marker({
position: props,
map: map
});
console.log(marker.getPosition().toUrlValue(6));
bounds.extend(marker.getPosition());
}
google.maps.event.addDomListener(window, "load", function() {
initMap(19.16, 75.857)
});
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
Currently, I'm developing a system that will bring all latitude and longitude from MySQLi DB, and will output every data on the page. Here is my PHP code (working without any problem):
header('Content-Type: text/html; charset=utf-8');
require('database.php');
$query = mysqli_query($mysqli, "SELECT * FROM `tracking`");
if (!$query)
{
die('Error: ' . mysqli_error($mysqli));
}
if(mysqli_num_rows($query) > 0){
$getList = array();
while ($row = mysqli_fetch_assoc($query)) {
$getList[] = $row;
}
for($i = 0, $l = count($getList); $i < $l; ++$i) {
echo $getList[$i]['lat'].",".$getList[$i]['lon']."\n";
}
}
e.g output: -71.99991299555996,-83.18116602 -22.809918399999997,-43.4211132 -22.8540416,-43.2488448
Now, I need bring all data and put into an array, and put whole latitude/longitude to markers in Google Maps. Check what I have tried:
var check = false;
function refreshAll() { // This function will be called every 60 seconds
var locations = [];
locations.length = 0;
$.ajax({
type: "GET",
url: "show.php",
success: function(x)
{
var items = x.split("\n");
for(i=0; i<items.length; i++){
var data = items[i];
if ((items[i]).length > 1) {
locations.push(items[i].trim());
}
}
if (check == false) { // this will avoid map refreshing, I need only markers update.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
check = true;
}
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
alert(locations[i]);
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].trim()),
map: map
});
}
}
});}
The problem is: the markers is not being set, and have no errors in console. I'm working on this in the last two days and can't find any solution. Can you help me? Thank you.
As you can see here in the docs, the LatLng object is different than the one you are using.
So, replace:
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].trim()),
map: map
});
With
locations[i] = locations[i].trim().split(',');
var latLng = {lat: Number(locations[i][0]), lng: Number(locations[i][1])};
marker = new google.maps.Marker({
position: latLng,
map: map
});
Check out, the map object is in your infoWindow variable, try to set there the positions.
This should be used inside the locations loop.
var pos = {
lat: latitude,
lng: longitude
};
infoWindow.setPosition(pos);
So i have a set of data in my database, the data consist of location id (loc_id), longitude, and latitude. what i want to do is to create a map that consist of marker from all of my location data. what should i do first to create this map? because this is my first time using javascript.
currently the code that i used to show the map :
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var mapProp = {
center:new google.maps.LatLng(-7.803164,110.3398252), zoom:10, mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You need to output the data in your database into javascript and then loop through them then add them to your map.
First get the data from your database and make it into a javascript array. FYI my PHP is very rusty
var locations = [
<?php
$query = 'SELECT * FROM sometable';
$result = mysql_query($query);
$currentrow = 0;
while ($row = mysql_fetch_assoc($result)) {
$currentrow++;
echo '{';
echo 'latitude : ' . $row[0] . ',';
echo 'longitude: ' . $row[1] ;
echo '}'.if(currentrow != msqli->num_rows){,}
}
?>
]
Then on the javascript you need to loop through the locations array and create them as markers.
for(var i = 0; i < locations.lengtht; i++){
var myLatLng = {
lat: locations[i].latitude,
lng: locations[i].longitude
};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Your title'
});
}
I'm trying to find a way to use the function initialize inside a php file.i parse the xml file with the file_get_contents
$xml = file_get_contents('http://www.123.org/upload/123.xml');
include 'xml_regex.php';
$news_items = element_set('item', $xml);
foreach($news_items as $item) {
$description = value_in('description', $item);
$glat = value_in( 'glat', $item );
$glon = value_in( 'glon', $item );
$item_array[] = array(
'description' => $description,
'glat'=>$glat,
'glon'=>$glon
);
}
the function initialize
</script>
function initialize() {
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng( 38.822590,24.653320 )
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
<?php foreach ( $item_array as $item ) {
//how can i use this lines inside the loop?
//var latlng = new google.maps.LatLng(parseFloat("<?php $glat ?>"),
//parseFloat("<?php $glon ?>"));
//alert (latlng);
//also inside the loop i wanna use the createMarker funciton
}?>
</script>
Any ideas?
Finally i found the way!Just quote the code.Maybe it will help someone in the future!
<?php foreach ( $item_array as $item ) : ?>
var latlng = new google.maps.LatLng(parseFloat(<?php echo $item['glat']; ?>),
parseFloat(<?php echo $item['glon']; ?>));
if ( '<?php echo $item["temp"]; ?>' <= "1 °C" ) {
var marker = createMarker( latlng,cold );
}
function createMarker( latlng,cold ) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: cold
});
return marker;
}