Javascript & PHP show multiple trackers in Google Maps API - javascript

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);

Related

Add a space after comma in an array

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.

Google maps api and geocoding api - issues adding markers

I will start by saying that I am relatively new to JS, so please forgive my ignorance if this is obvious.
I am trying to add markers to a google map. I have created an array coordList, then used the geocoding api to get the lag and long from the addresses and pushed them into coordList.
I am now trying to use the coordList array to plot markers on the map, however I cannot seem to get the values from the coordList array. When I run console.log(typeof coordList) - it tells me it's an object, but when i look at the array with console.log(coordList) it just looks like a normal array?
var coordList = [];
var address = [];
address.push('52+Kalynda+pde,+bohle+plains,+QLD')
address.push('51+Frank+St,+Kirwan+QLD+4817');
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(-19.259854,146.8001348),
mapTypeId: 'roadmap'
});
}
function getLatLong(address){
var index;
for (index = 0; index < address.length; ++index) {
var request = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address[index] + '&key=[MY_key]';
$.getJSON( request, function( data ) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
var coords = [];
coords.push(lat);
coords.push(lng);
//push coords into coordList
coordList.push(coords);
});
}
}
// Loop through the results array and place a marker for each
// set of coordinates.
function addMarkers(coordList) {
for (var i = 0; i < coordList.length; i++) {
var coords = coordList[i];
var latLng = new google.maps.LatLng(coords[0],coords[1]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
}
getLatLong(address);
addMarkers(coordList);
Your problem is that $.getJSON() is an asynchronous request and your code executes addMarkers() before than $.getJSON() finishes, so coordList is empty.
You can add the markers inside $.getJSON() callback. For example:
var address = [];
address.push('52+Kalynda+pde,+bohle+plains,+QLD')
address.push('51+Frank+St,+Kirwan+QLD+4817');
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(-19.259854,146.8001348),
mapTypeId: 'roadmap'
});
}
function getLatLongAndAddMarkers(address){
var index;
for (index = 0; index < address.length; ++index) {
var request = 'https://maps.googleapis.com/maps/api/geocode/json?dress=' + address[index] + '&key=[MY_key]';
$.getJSON( request, function( data ) {
var latLong = new google.maps.LatLng(data.results[0].geometry.location);
//add markers here
var marker = new google.maps.Marker({
position: latLong,
map: map
});
});
}
}
getLatLongAndAddMarkers(address);

Google Map Marker not working when from DB

I'm starting to learn Google Map. It's strange that when statically declared, markers are working and being displayed, but when they come from DB, they aren't being drawn on map.
// var markers = [[15.054419, 120.664785, 'Device1'], [15.048203, 120.692186, 'Device 2'], [15.033303, 120.694611, 'Device 3']];
var markers = [];
I have the entire code here, maybe I am missing something? I even used console log and I successfully pass all data from ajax to markers variable.
I think I got this code somewhere here in SO and modified it to fit in for my DB calls for records. I hope you can help me out on this one. Thank you!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
<script type="text/javascript">
var map;
var global_markers = [];
// var markers = [[15.054419, 120.664785, 'Device1'], [15.048203, 120.692186, 'Device 2'], [15.033303, 120.694611, 'Device 3']];
var markers = [];
var infowindow = new google.maps.InfoWindow({});
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(15.058607, 120.660884);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
$.ajax({
type: 'GET',
url: 'control_panel/get_device_list_ajax',
success:
function (data) {
data = JSON.parse(data);
if (data['success']){
var device = data['device_list'];
device.forEach(function (dev) {
markers.push([dev['dev_geolat'], dev['dev_geolng'], dev['dev_name']]);
//console.log(markers);
});
addMarker();
} else {
}
}
});
}
function addMarker() {
console.log(markers);
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var trailhead_name = markers[i][2];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = "<html><body><div><p><h2>" + trailhead_name + "</h2></p></div></body></html>";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Coordinates: " + lat + " , " + lng + " | Trailhead name: " + trailhead_name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function() {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
window.onload = initialize;
</script>
EDIT
Here is the jsfiddle I used to work with this one http://jsfiddle.net/kjy112/ZLuTg/ (thank you to the one that lead me to this)
Could be related to the way you accessing to json rendered by ajax
markers.push([dev.dev_geolat, dev.dev_geolng, dev.dev_name]);
or the json content
I don't know how to close this question as I overlooked some problems on my DB but I'll be posting my answer if someone may come with the same problem (well, I am not sure about that hehe)
I get the same response from AJAX of the values in DB and I am not able to draw markers on MAP, I found that db->table->fields LAT LNG are referenced with a data type of DECIMAL (7,5) and changed it to FLOAT (10, 6) as to what is found in this GOOGLE MAP Tutorial - Using PHP/MySQL with Google Maps.
The issue at the field before was that higher values tend to be saved as 99.999999 instead of the actual value (e.g. 120.XXXXX) .

Google Maps API marker based on data

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'
});
}

Pass resultset value to a javascript function

I have one resultset,
How can i pass its value to a javascript function ,and move internal pointer to next row.
<?php
$q=mysql_query("select * from tbl_map")or die(mysql_error());
$i=0;
?>
<script>
$(document).ready(function() {
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = null;
function autoUpdate() {
<?php
mysql_data_seek($q,$i);
$row=mysql_fetch_assoc($q);
$i++;
?>
lat=<?php echo $row['latitude']; ?>;
long=<?php echo $row['longitude']; ?>;
navigator.geolocation.getCurrentPosition(function(position) {
var newPoint = new google.maps.LatLng(lat,
long);
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
}
else {
// Marker does not exist - Create it
marker = new google.maps.Marker({
position: newPoint,
map: map
});
}
// Center the map on the new position
map.setCenter(newPoint);
});
// Call the autoUpdate() function every 5 seconds
setTimeout(autoUpdate, 5000);
}
autoUpdate();
});
</script>
I want to fetch latitude and longitude from database and pass to autoupdate()
but i can not move internal pointer ahead.
How to fix ?
Try this: in this method array of latitude and longitude is assigned to a javascript variable json in form of json data.
<script>
// ---- PHP Starts here which fetch data and is placed immediately after <script> tag open
// ---- and store to a variable in json format.
<?php
$q = mysql_query("select * from tbl_map")or die(mysql_error());
$response = array();
for($i = 0; $i < mysql_num_rows($q) ; $i++ )
{
mysql_data_seek($q, $i);
$row = mysql_fetch_assoc($q);
array_push( $response, array(
'lat'=>$row['latitude'],
'long'=>$row['longitude']
));
// ------ Here php assigns the array of data to `json`
// ------ `var json` is under scope of javascript
echo 'var json = ' . json_encode($response) . ';';
}
?>
// ---- PHP part ends here and javascript start
// ---- Testing the `json` var
console.log(json);
console.log(json.length);
$(document).ready(function() {
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var c = 0;
var marker = null;
function autoUpdate() {
console.log(json[c].lat);
console.log(json[c].long);
navigator.geolocation.getCurrentPosition( function(position)
{
var newPoint = new google.maps.LatLng( json[c].lat, json[c].long );
if (marker) {
// Marker already created - Move it
marker.setPosition(newPoint);
}
else {
// Marker does not exist - Create it
marker = new google.maps.Marker({
position: newPoint,
map: map
});
}
// Center the map on the new position
map.setCenter(newPoint);
});
if (c == (json.length - 1)) { c = 0; } else { c++; }
// Call the autoUpdate() function every 5 seconds
setTimeout(autoUpdate, 5000);
}
autoUpdate();
});
</script>

Categories