passing php array to javascript using ajax - javascript

I'm building something with Google Maps and Instagram. I'm trying to send the coordinates of the Instagram photos from my PHP file to my JavaScript file using AJAX. I basically have no idea how to handle this on the JavaScript side.
This is what my index.php file looks like:
<?php
$jsonText= file_get_contents("");
$instagram = json_decode($jsonText);
foreach ($instagram->data as $photo) {
$longitude = $photo->location->longitude;
$latitude = $photo->location->latitude;
$picture = $photo->images->thumbnail->url;
$results = array($latitude, $longitude, $picture);
echo json_encode($results, true);
}
?>
My js file looks like this:
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(45.525961, 15.255119)
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
$.ajax({
url: 'index.php',
dataType: 'json',
success: function(data) {
var location = new google.maps.LatLng();
var marker = new google.maps.Marker({
position: location,
map: map,
title:"Where the photo was taken.."
});
}
})
}

First of all, I would suggest you not to share your API Key/Access Token publicly.
I made slight changes to your code. This is the ajax call now,
$.ajax({url: 'test.php'}).done(function(data) {
// alert(data);
for (var i = data.length - 1; i >= 0; i--) {
for (var j = data[i].length - 1; j >= 0; j--) {
$("#someElement").append(data[i][j]);
};
};
}
);
You can use the data as you wish.

Related

Javascript & PHP show multiple trackers in Google Maps API

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

How to update map data throug ajax

I am trying to update map data through ajax but ist's not working here is my code:
$(document).ready(function() {
function makeRequest(){
$.ajax({
url:"<?php echo Url::base(true).'/users/online-peoples'; ?>",
type:"POST",
})
.done(function(result){
var icon1 = 'https://mt.googleapis.com/vt/icon/name=icons/onion/27-cabs.png&scale=1.0';
if(result){
var map;
function initMap() {
var infowindow = new google.maps.InfoWindow();
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng('30.7333','76.7794'),
mapTypeControlOptions: {
mapTypeIds: ['roadmap']
}
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var online =result;
var mapIcons = ['https://mt.googleapis.com/vt/icon/name=icons/onion/27-cabs.png&scale=1.0'];
var person = {3:"Customer1 : ", 4:"Driver1 : "};
var arr = [];
var marker, i;
for (i = 0; i < online.length; i++)
{
console.log(online[i]);
arr.push(new google.maps.LatLng(online[i][0], online[i][0]));
marker = new google.maps.Marker({
position: new google.maps.LatLng(online[i][0], online[i][1]),
icon:mapIcons[0],
suppressMarkers: true,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(person[online[i][4]]+online[i][2]+', Phone : '+online[i][5]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
}
});
}
setInterval(makeRequest, (10 * 1000));
});
The above code update map icons and date every 10 secondas but it's not working.Where i am doing wrong ?
This is my data :
[
["30.740395","76.7804482","Dbd Dbdhdh","1",4],
["30.740395","76.7804482","Sam Sam","1",4],
["30.7404344","76.7804032","Sumit Kumar","1",4],
["30.74041018","76.78060575","Chetan Nagrath","3",4],
["30.7403555","76.7804933","Sahil Kapoor","2",4],
["30.7403648","76.7805835","paras kumar",1,3]
]
You are not initializing your map. Since its inside initMap map function no one is calling it.
And there is no need to initialize every time when you got the data from the server. Just initialize once and use the same map object for your other works also.
And be careful while getting the data, You are trying to get the data in the index 5. But the array has only 0 to 4.
Try in the below fashion.
$(document).ready(function() {
function makeRequest() {
$.ajax({
url : "url",
type : "POST",
}).done(function(result) {
if (result) {
console.log("You Got your data", result);
}
});
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom : 12,
center : new google.maps.LatLng('30.7333', '76.7794'),
mapTypeControlOptions : {
mapTypeIds : [ 'roadmap' ]
}
});
setInterval(makeRequest, (10 * 1000));
});
Here you will get data after 10 second. If you want at the first time itself means call makeRequest after initialization of map once.

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>

Update markers from google maps using codeigniter, Ajax, Javascript, Php

I have a google map on my website created in codeigniter. Now I want to move the markers with data from my sql database. The data in my database will be updated. I can draw markers on the map by biostall. Now I want to move them.
So I load all the markers and pass them to my view to draw them with a ajax/javascript script. I get no errors but also no markers.. I'm not a pro in ajax and javascript so the problem needs to be there but I can't fix it.. Here's my code. The map should be updated each 3 seconds.
My controller :
function render_maps() {
$userid = $this->uri->segment(3);
$userlevel = $this->user_model->get_user_level($userid);
if ($userlevel > 2) {
$this->load->library('googlemaps');
$this->googlemaps->initialize();
#$this->marks();
$config['zoom'] = 'auto';
$data['map'] = $this->googlemaps->create_map();
$data['markers'] = json_encode($this->user_model->get_marks());
$data['userdata'] = $this->session->userdata;
$this->load->view('header', $data);
$this->load->view('dashboard_maps', $data);
$this->load->view('wrapper', $data);
}
}
My view :
<head>
<?php echo $map['js']; ?>
<script type="text/javascript">
function refreshMarkers() {
$.ajax({
url: "<?php site_url('User/render_maps/'. $this->session->userdata('user_id')) ?>",
type: "POST",
data: ({value: $markers}),
dataType: "json", //retrieved Markers Lat/lng in Json, thus using this dataType
success: function(data){
//Removing already Added Markers//////////
for (var i = 0; i < $markers.length; i++) {
$markers[i].setMap(null);
}
$markers = new Array();
//////////////////////////////////////////
// Adding New Markers////////////////////
for (var i = 0, len = data.length; i < len; ++i) { // Iterating the Json Array
var d = data[i];
var lat = parseFloat(d.lat);
var lng = parseFloat(d.lng);
var myLatlng = new google.maps.LatLng(lat, lng);
var marker = {
map: map,
position: myLatlng // These are the minimal Options, you can add others too
};
createMarker(marker);
}
}
}
);
</script>
Your function refreshMarkers() is missing a closing } bracket. Please also include all dependencies such as jquery and other functions.
You don't have to be a pro in ajax or javascript to achieve that. Make sure you retrieve the data successfully using your browser's console.
Here's a vanilla example for Google Map JS API with multiple markers which shows different earthquake locations. Try running the code snippet below.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style type="text/css">
html, body { height: 100%; margin: 0; padding: 0; }
#map { height: 100%; }
</style>
</head>
<body>
Click Here >> <button id="earthquakes">Show Earthquakes</button>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDrhmCE5YeH0r9Kkeq-v4ZXBd87UvwCOrw&callback=initMap">
</script>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 4.8259171, lng: 63.3691405},
zoom: 1
});
}
function createMarker(latlng, name) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: name
});
}
function displayMarkers() {
console.log('displayMarkers:'+latitd+':'+longtd+'\n');
var latlng = new google.maps.LatLng(latitd, longtd);
var name = titleName;
createMarker(latlng, name);
}
var latitd;
var longtd;
var titleName;
var nowDate = new Date();
var displayDate = nowDate.toJSON().slice(0,10);
nowDate.setDate(nowDate.getDate() - 1);
var yesterDate = nowDate.toJSON().slice(0,10);
$(document).ready(function() {
$('#earthquakes').click(function() {
getQuakes();
});
function getQuakes() {
console.log('yesterDate:'+yesterDate+', displayDate:'+displayDate+'\n');
$.ajax({
url: 'http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=' + yesterDate + '&endtime=' + displayDate,
dataType : 'json'
})
.done(function(data) {
console.log('data.features:'+data.features);
$.each(data.features, function(key, val) {
var coord = val.geometry.coordinates;
locationD = {
latd: coord[0],
lngd: coord[1]
};
latitd = locationD.latd;
longtd = locationD.lngd;
titleName = val.properties.title;
console.log(latitd, longtd);
console.log(titleName);
displayMarkers();
});
})
.fail(function(e){
console.log(e);
})
.always(function(){
console.log('ajax executed');
});
}
});
</script>
</body>
</html>

Laravel and Geocoding markers (nearby users) do not update correctly

I try to show on a google map markers that are near the current positon. If the map is dragged it will update the center coordinates and recalculate the markers around that center. The initial markers around the current users positon are showing correctly but when i drag the map they stay all the time the same. The update and the POST both is happening (my guess that the POST is not finished before the markers reload, so the old ones stay). The sourrounding markers are stored in a session variable.
Controller showNearbyUsers method:
/**
* Shows the users near the current one
*
* #return void
*/
public static function showNearbyUsers($centerlat,$centerlng)
{
try {
// Delete the session variable
if (Session::has('nearbies'))
{
Session::forget('nearbies');
}
// Define max, min for lat and lng
$centerlatlow = $centerlat-0.25;
$centerlathigh = $centerlat+0.25;
$centerlnglow = $centerlng-0.25;
$centerlnghigh = $centerlng+0.25;
$nearbies = DB::table('positions')->join('users', 'users.id', '=', 'positions.users_id')
->where('users_id', '!=', Auth::id())
->whereBetween('lat', array($centerlatlow, $centerlathigh))
->whereBetween('lng', array($centerlnglow, $centerlnghigh))
->select('positions.*', 'users.name', 'users.level')
->get();
if ($nearbies) {
return Session::put('nearbies', $nearbies);
}
} catch(\Exception $e) {
Session::flash('message', 'An error occured with your localization. Enable GPS and refresh.');
Session::flash('alert-class', 'alert-danger');
}
}
View Script
<script>
// Auto adjust map div
$(window).resize(function () {
var h = $(window).height(),
offsetTop = 220; // Calculate the top offset
$('#map_canvas').css('height', (h - offsetTop));
}).resize();
// Setup token security
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
// Attributes
var map;
var geocoder;
var markers = Array(); // Contains x,y
var users = Array(); // Contains whole user info
var current = Array();
var infoWindows = Array();
var mapCenter;
// Test initialize users array
//users = [['Brugg',47.47963,8.18465],['Aarau',47.39340,8.04312],['Baden',47.47377,8.30647]];
// Initialize the map with logged in user
function initialize() {
geocoder = new google.maps.Geocoder();
getLocation();
}
// Set nearby user markers
function setMarkers(list) {
for(var i=0; i<list[0].length; i++){
var element = (list[0])[i];
var nearbyLatLng = new google.maps.LatLng(element['lat'], element['lng']);
console.log((list[0])[i]);
markers[i] = new google.maps.Marker({
position: nearbyLatLng,
map: map,
title: element['name'],
infoWindowIndex : i
});
infoWindows[i] = new google.maps.InfoWindow({
content : element['name']
});
google.maps.event.addListener(markers[i], 'click',
function(event)
{
infoWindows[this.infoWindowIndex].open(map, this);
}
);
}
}
// Delete nearby user markers
function deleteMarkers() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
// Map dragging listener. Updates the nearby users markers
function mapDragListener() {
google.maps.event.addListener(map, 'dragend', function() {
deleteMarkers();
mapCenter = map.getCenter();
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
async: false
});
#if(Session::has('nearbies'))
<?php $test = Session::get('nearbies'); ?>
users = [<?php echo json_encode($test); ?>];
console.log(users);
#endif
setMarkers(users);
});
}
// Map zoom listener. Updates the nearby users markers
function mapZoomListener() {
}
// Get current user location
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
} else {
alert("Geolocation is not supported by this browser.");
}
}
// If success in finding current position
function geoSuccess(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// Send to geocoordinates.php and save to DB
$.post("updateme/"+lat+"/"+lng);
mainMapCalc(lat, lng);
}
// If no success in finding current position
function geoError() {
alert("Please enable Geo-Location and Refresh the Website.");
}
// Set the logged in users and build up the environment
function mainMapCalc(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if(results[1]) {
//formatted address
var address = results[0].formatted_address;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 18,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
mapCenter = map.getCenter();
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
async: false
});
<?php $test = Session::get('nearbies'); ?>
users = [<?php echo json_encode($test); ?>];
setMarkers(users); // Set initial nearby markers
mapDragListener(); // Register Listener
//mapZoomListener(); // TODO: Register Listener
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
} else {
alert("Geocoder Error// No results found");
}
} else {
alert("Geocoder Error// Failed due to: " + status);
}
});
}
// Show Map
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Where is here the problem?
Thanks in advance
It looks like the problem is that you are sending out the ajax request, but you are not doing anything with the returned data. Try changing
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
async: false
});
to
$.ajax({
type: "POST",
url: "updatenearbies/"+mapCenter.lat()+"/"+mapCenter.lng(),
success: function(data, textStatus, jqXHR) {
// request succeeded
// data - response from server
},
error: function (jqXHR, textStatus, errorThrown){
// the request failed
}
});
Also note that async: false is deprecated: https://api.jquery.com/jQuery.ajax/#options, so you should use callbacks as shown above.

Categories