Load data from database/model with Ajax - javascript

I'm creating a Google Maps application. I need to load location data from a database with Ajax, so I can show these data every x seconds. I'm using CodeIgniter/PHP. This is what I got:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
httpCall();
}
function httpCall($http) {
$http({
method: 'GET',
url: '<?php echo site_url('User/marks') ?>',
data: data,
dataType: "json"
})
.success(function (data) {
for (var i = 0, len = markers.length; i < len; ++i) {
var myLatLng = {lat: markers[i].lat, lng: markers[i].lng};
var marker = new google.maps.Marker({
position: {
lat: parseFloat(markers[i].lat),
lng: parseFloat(markers[i].lng)
},
map: map
});
}
})
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"
async defer></script>
</body>
</html>
the User/marks function is:
function marks() {
echo json_encode($this->user_model->get_marks());
}
user_model get marks function is:
function get_marks() {
$sql = "select lat,lng
from tbl_locations";
$query = $this->db->query($sql);
$result = $query->result();
return $result;
}
My error is:
ReferenceError: data is not defined
Apparently I pass the data incorrectly, but what is the correct way?

Store your json result in an array
function marks() {
echo json_encode(array('data'=>$this->user_model->get_marks()));
}
and try to print the result of data by using console.log(data) in your ajax result.

That's because you didn't define data variable, which you are passing through data: data, You have to define it in function httpCall($http) then pass it in ajax function

Related

google map api markers with realtime data

I currently have realtime analytics php api. It has this entity named $resulting. If I do print_r($resulting); it returns for example (if only 1 user is online):
Array ( [0] => Array ( [0] => Arnhem [1] => 5.898730 [2] => 51.985104 [3] => Chrome [4] => DESKTOP [5] => / [6] => 1 ) )
Now, later on in the same file, I have the google maps javascript api.
It has markers in the form of:
var markers = [
{
coords:{lat:52.0907,lng:5.1214},
content:'<h1>Utrecht</h1>'
},
{
coords:{lat:52.0907,lng:5},
content:'<h1>Links</h1>'
},
{
coords:{lat:52.0907,lng:6},
content:'<h1>Rechts</h1>'
}
];
As placeholder for now.
What I want to do, is have in the coords: section have the lat: and lng: be the appropriate values from $resulting.
Also, I want to have as many markers as there are users online.
Now, I have tried everything I can think of, but I can't get it to work.
I have tried for example:
const results = <? php echo json_encode($resulting); ?>;
let markers = [];
for(let i = 0; i < results.length; i++) {
markers[i] = {
coords: {
lat: results[1],
lng: results[2]
}
};
}
but then the maps won't load anymore.
I have tried looping, foreach, trying to get the lat: and lng: to update with the values returned by $resulting, but whatever I do it simply won't work.
Can anybody help me and get this working?
Thanks.
edit:
adding the index.php file as requested:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="jquery.json-2.4.min.js"></script>
<title>My Google Map</title>
<style>
#map{
height: 400px;
width:400px;
}
</style>
</head>
<body>
<h1>My Google Map</h1>
<div id="map"></div>
<?php
require_once __DIR__ . '/../google/vendor/autoload.php';
$analytics = initializeAnalytics();
function initializeAnalytics()
{
// Creates and returns the Analytics Reporting service object.
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = __DIR__ . 'MY KEY FILE LOCATION';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_Analytics($client);
return $analytics;
}
/**
* 1.Create and Execute a Real Time Report
* An application can request real-time data by calling the get method on the Analytics service object.
* The method requires an ids parameter which specifies from which view (profile) to retrieve data.
* For example, the following code requests real-time data for view (profile) ID 56789.
*/
$optParams = array(
'dimensions' => 'rt:city, rt:longitude, rt:latitude, rt:browser, rt:deviceCategory, rt:pagePath');
try {
$resultsrealtime = $analytics->data_realtime->get(
'ga:MY GOOGLE CLIENT ID',
'rt:activeUsers',
$optParams);
// Success.
} catch (apiServiceException $e) {
// Handle API service exceptions.
$error = $e->getMessage();
}
/**
* 2. Print out the Real-Time Data
* The components of the report can be printed out as follows:
*/
$resulting = $resultsrealtime->getRows();
function test() {
if(count($resulting == false)){
return;
}
else if(count($resulting) > 0){
foreach ($resulting as $resultingTwo => $resultingThree) {
foreach ($resultingThree as $resultingFour){
echo $resultingFour.'<br />';
}
}
} else {
echo 'No visitors';
}
}
?>
<script>
// Map options
function initMap(){
var options = {
zoom:7,
center:{lat:52.0907, lng:5.1214}
}
// New map
var map = new google.maps.Map(document.getElementById('map'), options);
// Array of markers
var markers = [
{
coords:{lat:52.0907,lng:5.1214},
iconImage:'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
content:'<h1>Utrecht</h1>'
},
{
coords:{lat:52.0907,lng:5},
content:'<h1>Links</h1>'
},
{
coords:{lat:52.0907,lng:6},
content:'<h1>Rechts</h1>'
}
];
// Loop through markers
for(var i = 0; i < markers.length; i++){
// add Marker
addMarker(markers[i]);
}
// Add Marker Function
function addMarker(props){
var marker = new google.maps.Marker({
position: props.coords,
map:map,
//icon:props.iconImage
});
// Check for custom icon
if(props.iconImage){
// Set icon image
marker.setIcon(props.iconImage);
}
// Check for content
if(props.content){
// Set content
// Info Window
var infoWindow = new google.maps.InfoWindow({
content:props.content
});
marker.addListener('mouseover', function(){
infoWindow.open(map, marker);
// Reset Info Window
setTimeout(function(){
infoWindow.open()
}, 500);
}, false);
}
}
}
</script>
<div id="data"><p><?php $test = json_encode($resulting); print_r($test);?></p></div>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuvHNJq4R6v_62R03EVG0n8UdIzXTEiI4&callback=initMap">
</script>
</body>
</html>
Also, what the json_encode returns with 2 users online:
[["Arnhem","5.898730","51.985104","Chrome","DESKTOP","\/","1"],["Eindhoven","5.469722","51.441643","Chrome","MOBILE","\/","1"]]
You should also assign the map object to the marker (assuming your map object is named map )
for(let i = 0; i < results.length; i++) {
markers[i] = {
coords: {
lat: results[1],
lng: results[2]
},
map: map
};
}
To help you identify the issue, it would be useful to see the rest of your javascript code for the map api, as well as the array when there's more than one user after running it though json_encode(). That said, try the following:
const results = <? php echo json_encode($resulting); ?>;
for(let i = 0; i < results.length; i++) {
let marker = new google.maps.Marker({
position: {lat: results[1], lng: results[2]},
content: '<h1>' + results[0] + </h1>,
map: map
});
}
Edit:
I don't have Composer installed in the directory I tested your code in, and I haven't worked much with the Google realtime API, but the following javascript will work given the output you listed for $resulting. You'll have to tweak things depending on where your custom icons are coming from, but that should be pretty straightforward.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="jquery.json-2.4.min.js"></script>
<title>My Google Map</title>
<style>
#map{
height: 400px;
width:400px;
}
</style>
</head>
<body>
<h1>My Google Map</h1>
<div id="map"></div>
<?php $resulting = array(array("Arnhem","5.898730","51.985104","Chrome","DESKTOP","\/","1"), array("Eindhoven","5.469722","51.441643","Chrome","MOBILE","\/","1")); ?>
<script>
const resultingArr = <?php echo json_encode($resulting); ?>;
function initMap() {
var options = {
zoom: 7,
center: {
lat: 52.0907,
lng: 5.1214
}
}
var map = new google.maps.Map(document.getElementById('map'), options);
function mapMarkers(props) {
const marker = new google.maps.Marker({
position: props.coords,
map: map,
icon: props.iconImage
});
const infoWindow = new google.maps.InfoWindow({
content: props.content
});
marker.addListener('mouseover', function() {
infoWindow.open(map, marker);
});
marker.addListener('mouseout', function() {
infoWindow.close();
});
}
for (let i = 0; i < resultingArr.length; i++) {
mapMarkers({
coords: {
lat: parseFloat(resultingArr[i][2]),
lng: parseFloat(resultingArr[i][1])
},
content: '<h3>' + resultingArr[i][0] + '</h3>'
})
}
};
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuvHNJq4R6v_62R03EVG0n8UdIzXTEiI4&callback=initMap">
</script>
</body>
</html>
Hope this helps!

Google is not defined (api maps error)

After being reading some time... I wanted to start use the Google Maps API for Javascript. I got the key on their website, I tried many ways to create maps but now, I want to create a map by a previous "location" so first, I use the Geocoder.geocode() and then I create the map, last night it was working okey.
So, I decided to start use overlays (Markers) in these maps but I don't know I'm getting the Uncaught error: google is not defined.
I read a bit about it and i know most of times is about asynchronous problem but, I still don't know how fix it, here is the code:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body { height: 100%; margin: 0; padding: 0; }
#map { height: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAeaWLxSHFEdwWEVVYajslt7R9eP0ZpLXQ&callback=initMap"></script>
<script type="text/javascript">
var sLocation = "Castillejos 265 Barcelona";
var sLocationToSearch =sLocation.split(' ').join('+');
$.ajax({
type: 'GET',
url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+ sLocationToSearch +'&key=AIzaSyAeaWLxSHFEdwWEVVYajslt7R9eP0ZpLXQ',
success: function(res){
// ParseFloat the <latitud> and <longitud>
//var myLatlng = new google.maps.LatLng(parseFloat(trader.geo.lat),parseFloat(trader.geo.lon));
initMap(res.results[0].geometry.location);
},
error: function(error){
console.log(error);
}
});
function initMap(oLatlng){
var map = new google.maps.Map(document.getElementById('map'), {
center: oLatlng,
zoom: 15
});
}
</script>
</body>
</html>
thanks a lot for your help
call javascript after page is loaded by using window.onload
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html, body
{
height: 100%;
margin: 0;
padding: 0;
}
#map
{
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAeaWLxSHFEdwWEVVYajslt7R9eP0ZpLXQ&callback=initMap"></script>
<script type="text/javascript">
window.onload = function()
{
var sLocation = "Castillejos 265 Barcelona";
var sLocationToSearch = sLocation.split(' ').join('+');
$.ajax({
type : 'GET',
url : 'https://maps.googleapis.com/maps/api/geocode/json?address=' + sLocationToSearch + '&key=AIzaSyAeaWLxSHFEdwWEVVYajslt7R9eP0ZpLXQ',
success : function(res)
{
// ParseFloat the <latitud> and <longitud>
//var myLatlng = new google.maps.LatLng(parseFloat(trader.geo.lat),parseFloat(trader.geo.lon));
initMap(res.results[0].geometry.location);
},
error : function(error)
{
console.log(error);
}
});
function initMap(oLatlng)
{
var map = new google.maps.Map(document.getElementById('map'), {
center : oLatlng,
zoom : 15
});
}
}
</script>
</body>
</html>

add a marker on existing map from data received by web service

I want to add a marker into existing google map, from data received by my web service. I get the latitude and the longitude with no problems. But I canĀ“t figure out how to this. Here go my code, and what I try to do:
<html>
<head>
...
<script>
function initialize(){
var mapProp = {
center:new google.maps.LatLng(25,-30),
zoom:2,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap") ,mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
...
<div class="col-md-8">
<div id="googleMap" style="width:700px;height:350px; border-radius:20px;"></div>
</div>
...
<script src="../front-end/js/main.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#jogadoresList").click(function () {
$("#index").hide();
$("#selecoes").hide();
$("#jogador").show();
initialize();
});
});
</body>
main.js
function findByIdLocationTwitterJogador(id){
console.log('findJTwitterByJogadorrrrrr AQUIIIIIIIIII' + id);
$.ajax({
type: 'GET',
url: rootURLLocalizacao +'/' + id,
dataType: "json", // data type of response
success: renderListLocalizacao
});
}
function renderListLocalizacao(data) {
// JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one')
var list = data == null ? [] : (data.dados instanceof Array ? data.dados : [data.jogo]);
$.each(list, function(index, jogo) {
var myLatlng = new google.maps.LatLng(jogo.latitude,jogo.longitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Former About.com Headquarters"
});
});
}
The issue here is that the "map" object is not visible from the renderListLocalizacao(...) function. Note how your map is created inside the scope of your initialize()
Try making the map a global var. If you dump / look at its value while running that function, I am guessing you will see map as undefined.
Please set a global map object as follows
<script>
var globalMap=null;
function initialize(){
var mapProp = {
center:new google.maps.LatLng(25,-30),
zoom:2,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
globalMap=new google.maps.Map(document.getElementById("googleMap") ,mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
and in renderListLocalizacao
function renderListLocalizacao(data) {
// JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one')
var list = data == null ? [] : (data.dados instanceof Array ? data.dados : [data.jogo]);
$.each(list, function(index, jogo) {
var myLatlng = new google.maps.LatLng(jogo.latitude,jogo.longitude);
var marker = new google.maps.Marker({
position: myLatlng,
map: globalMap,
title:"Former About.com Headquarters"
});
});

How can I read the json data from json file in google map api

I am trying to make a google map api with markers, which will show the latitude and longitude of some places.I am trying to do this with json file but it is not working..
here is my code ..
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cluster Map</title>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js" type="text/javascript"></script>
<script type="text/javascript">
var map;
var markers = [];
function initialize() {
geocoder = new google.maps.Geocoder();
var center = new google.maps.LatLng(43.474144,-112.03866);
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
markMultiple();
}
function markMap(latLng, content){
var marker = new google.maps.Marker({
position: latLng
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(content);
infowindow.open(map, marker);
});
markers.push(marker);
}
function markMultiple(){
$.parseJSON('test.json', function(data) {
$.each(data.markers, function(i, obj) {
var latLng = new google.maps.LatLng(obj.lat,obj.lng);
var content = obj.id + ':' + obj.lat + ',' + obj.lng;
markMap(latLng, content);
});
});
var markerCluster = new MarkerClusterer(map, markers);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-container">
<div id="map"></div>
</div>
</body>
please help me..
Engineer was right, you need to use $.getJSON method, $.parseJSON takes a JSON string, it doesn't load an external file.
getJSON: http://api.jquery.com/jQuery.getJSON/
parseJSON: http://api.jquery.com/jQuery.parseJSON/
I put your code in a jsFiddle and it is working with getJSON and an alternative test JSON file (you didn't provide the original test.json you're using).
$.getJSON('test.json', function(data) {
$.each(data.markers, function(i, obj) {
var latLng = new google.maps.LatLng(obj.lat,obj.lng);
var content = obj.id + ':' + obj.lat + ',' + obj.lng;
markMap(latLng, content);
});
});
http://jsfiddle.net/WYfjv/
If your code is not working maybe your JSON is not well formatted (try JSONLINT to test it). Also, if you are already improving, I would advise to use a normal for loop rather than $.each :)

Google Maps how to get to show only one marker?

i've been dealing with this couple of hours and i still cant figure how to do it.
my objective is to display only one marker when searching addresses close to each other.
below you have the code i use in my html in order to search for addresses, note - i'm developing a windows application that does such, in which case you might find some missing stuff to do actions by clicking buttons since this is done via .NET windows application
html code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=true&language=es"></script>
<script type="text/javascript">
var G = google.maps;
var map;
var geocoder = new G.Geocoder();
var marker;
var markersArray = [1];
function initialize() {
createMap();
geocode('Chicago');
}
function createMap() {
var myOptions = {
center: new G.LatLng(0,0),
zoom: 17,
mapTypeId: G.MapTypeId.ROADMAP
}
map = new G.Map(document.getElementById("map_canvas"), myOptions);
}
function geocode(address){
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
if (status == G.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new G.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
reading previous posts i know that if/else statement has to be used but cant get it right.
your help is very appreciated.
Leo P.
You can add a small bit of code to the beginning of your Geocode function that will remove the previous marker before setting a new one. Try this:
function geocode(address){
if (marker) {
marker.setMap(null);
}
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
Create only one marker as a global variable and change its position as needed. Like that you also save memory because you're not creating a new marker object on each request:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style>
html, body {width:100%; height:100%}
</style>
<script type="text/javascript" src="http://maps.google.com.mx/maps/api/js?sensor=true&language=es"></script>
<script type="text/javascript">
var G = google.maps;
var map;
var marker;
var geocoder = new G.Geocoder();
function initialize() {
createMap();
geocode('Chicago');
}
function createMap() {
var myOptions = {
center: new G.LatLng(0,0),
zoom: 17,
mapTypeId: G.MapTypeId.ROADMAP
}
map = new G.Map(document.getElementById("map_canvas"), myOptions);
// Create a single marker, (global variable), and don't give it a position just yet.
marker = new G.Marker({
map: map,
animation: google.maps.Animation.DROP,
});
}
function geocode(address){
geocoder.geocode({ 'address': (address ? address : "Miami Beach, Florida")}, function (results, status) {
if (status == G.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
//Position the marker
marker.setPosition(results[0].geometry.location);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>

Categories

Resources