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>
Related
I making my own real time youtube subscriber counter but refresh time is to high and when I change refresh time it not happening. Can someone tell me what I am doing wrong?
<html>
<head>
<link rel="stylesheet" href="odometer-theme-default.css"/>
<script src="odometer.js"></script>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<style>
.odometer {
font-size:100px;
}
#ytName {
font-size: 52px;
font-family:Arial;
}
</style>
</head>
<script type="text/javascript">
$(document).ready( function() {
var chanName = "";
loadChannel("UCPKqr9qSEXi6r03B18wRj6g");
function loadChannel(name) {
chanName = name;
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+name+'&key=AIzaSyBPIHea9sWYMSxe8W-tIn7OUvIw-dagDDI';
$.getJSON(url, function(data) {
$("#odometer").html(data.items[0].statistics.subscriberCount);
});
var url1 = 'https://www.googleapis.com/youtube/v3/channels?part=snippet&id='+chanName+'&key=AIzaSyBPIHea9sWYMSxe8W-tIn7OUvIw-dagDDI';
$.getJSON(url1, function(data) {
$('#ytName').html(data.items[0].snippet.title);
$('#ytLink').html('Link');
});
}
setInterval( function() {
var url = 'https://www.googleapis.com/youtube/v3/channels?part=statistics&id='+chanName+'&key=AIzaSyBPIHea9sWYMSxe8W-tIn7OUvIw-dagDDI';
$.getJSON(url, function(data) {
$("#odometer").html(data.items[0].statistics.subscriberCount);
}, 1000);
});
});
</script>
<body background = "bg.jpg">
<center>
<div id="ytName"></div>
<div id="ytLink"></div>
<div id="odometer" class="odometer"></div>
</center>
</body>
Maybe javascript should be written differently?
if you write the new time in milliseconds, the response is a bit
setInterval( function() {
// update code is here
}, 1000)
I'm new in airconsole, and I just learning it, so maybe this is something usual.
I have this at screen.html:
<html>
<head>
<script type="text/javascript" src="https://www.airconsole.com/api/airconsole-1.7.0.js"></script>
<script type="text/javascript">
var air_console = new AirConsole();
// Listen for messages from other devices
air_console.onMessage = function(from, data) {
// We receive a message -> Send message back to the device
air_console.message(from, "Full of pixels!");
// Show message on device screen
var info = document.createElement('DIV');
info.innerHTML = data;
document.body.appendChild(info);
};
</script>
<style type="text/css">
color: white;
</style>
</head>
<body>
</body>
</html>
And I have this in controller.html
<html>
<head>
<script type="text/javascript" src="https://www.airconsole.com/api/airconsole-1.7.0.js"></script>
<script type="text/javascript">
var air_console = new AirConsole();
// Send a message to the screen
air_console.message(AirConsole.SCREEN, "How are you?");
// Listen for messages
air_console.onMessage = function(from, data) {
// Show message on device screen
var info = document.createElement('DIV');
info.innerHTML = data;
document.body.appendChild(info);
};
</script>
<style type="text/css">
color: white;
</style>
</head>
<body>
</body>
</html>
And I got this error in both of them:
Uncaught TypeError: Cannot read property 'undefined' of undefined
at AirConsole.onPostMessage_ (airconsole-1.7.0.js:1012)
at airconsole-1.7.0.js:927
And of course nothing on the screen. What is my mistake here, how can I resolve this?
You need to wait for the onReady event before sending a message:
<html>
<head>
<script type="text/javascript" src="https://www.airconsole.com/api/airconsole-1.7.0.js"></script>
<script type="text/javascript">
var air_console = new AirConsole();
air_console.onReady = function() {
// Send a message to the screen
air_console.message(AirConsole.SCREEN, "How are you?");
}
// Listen for messages
air_console.onMessage = function(from, data) {
// Show message on device screen
var info = document.createElement('DIV');
info.innerHTML = data;
document.body.appendChild(info);
};
</script>
<style type="text/css">
color: white;
</style>
</head>
<body>
</body>
</html>
So I have this example geolocation app in HTML5 and Javascript that is supposed to display the user's current location on google maps. For some reason, I cannot get this to work, even though all of my privacy settings are enabled. In my browser and my Cordova preview, the page is still blocked from tracking my location. I got the example code from https://mobiforge.com/design-development/html5-mobile-web-a-guide-geolocation-api where the example app works when I click on the link on the webpage. Any ideas why this isn't working? Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>mobiForge geolocation map API demo</title>
<style>
body,html {height:100%}
#map {width:100%;height:100%;}
</style>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDbnJWPQoF5XQgI-akwQjyB6GKOFNtDO54"></script>
<script>
var map;
function initGeolocation() {
if (navigator && navigator.geolocation) {
var watchId = navigator.geolocation.watchPosition(successCallback,
errorCallback,
{enableHighAccuracy:true,timeout:60000,maximumAge:0});
} else {
console.log('Geolocation is not supported');
}
}
function errorCallback() {}
function successCallback(position) {
var myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
if(map == undefined) {
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
}
else map.panTo(myLatlng);
}
</script>
</head>
<body onload="javascript:initGeolocation()">
<div id="map">
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="script-src 'self' https://maps.googleapis.com/ https://maps.gstatic.com/ https://mts0.googleapis.com/ 'unsafe-inline' 'unsafe-eval'">
<script src="https://maps.googleapis.com/maps/api/js?key=Your_API_KEY&libraries=places" async defer></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script src="css/jquery-ui.css"></script>
<script src="js/jquery.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script type="text/javascript">
var map;
var latitude;
var longitude;
var mapOptions;
var myLatLan;
document.addEventListener("deviceready", function() {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}, false);
function onSuccess(position){
latitude=position.coords.latitude;
longitude=position.coords.longitude;
myLatLan={lat:latitude,lng:longitude};
console.log(myLatLan);
mapOptions={
zoom: 8,
center: myLatLan
};
}
function onError(error){
alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}
function showmap(){
var div = document.getElementById("map_canvas");
map = new google.maps.Map(div,mapOptions);
myLatLng={lat:latitude,lng:longitude};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
</head>
<body>
<h3>GoogleMaps-Plugin</h3>
<div style="width:100%;height:400px" id="map_canvas"></div>
<button id="button" onclick="showmap()">Full Screen</button>
</body>
</html>
You have not mentioned url white listing , the meta tag as u can see above has that .
Hope this Helps.
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
I'm going through Foursquare's tutorial and am getting this error message when I try to load the page:
Connecting failed
This app has a configuration problem and was unable
to connect to your Foursquare account.
Cause of error: Callback uri is not valid for this consumer
The code is the exact same as the sample code with my credentials subbed in. Is my Foursquare Client id not the right thing to use as the apiKey under config?
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>foursquare :: Explore Sample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" id="jquery"></script>
<link href="/styles/leaflet.css" type="text/css" rel="stylesheet" />
<link href="/styles/apisamples.css" type="text/css" rel="stylesheet" />
<script src="/scripts/apisamples.js" type="text/javascript"></script>
<script src="/scripts/third_party/jquery.ba-bbq.js" type="text/javascript"></script>
<script src="/scripts/third_party/leaflet.js" type="text/javascript"></script>
<script src="/scripts/third_party/wax.leaf.min.js" type="text/javascript"></script>
<style type="text/css">
html { height: 100%; }
body { height: 100%; margin: 0; padding: 0; }
/* Give our markers a background image */
.leaflet-marker-icon {
background: url(https://foursquare.com/img/pin-blue-transparent.png);
padding: 6px;
padding-bottom: 17px;
top: -6px;
left: -6px;
}
</style>
<script type="text/javascript">
var config = {
apiKey: '[my Foursquare Client id]',
authUrl: 'https://foursquare.com/',
apiUrl: 'https://api.foursquare.com/'
};
//<![CDATA[
/* Attempt to retrieve access token from URL. */
function doAuthRedirect() {
var redirect = window.location.href.replace(window.location.hash, '');
var url = config.authUrl + 'oauth2/authenticate?response_type=token&client_id=' + config.apiKey +
'&redirect_uri=' + encodeURIComponent(redirect) +
'&state=' + encodeURIComponent($.bbq.getState('req') || 'users/self');
window.location.href = url;
};
if ($.bbq.getState('access_token')) {
// If there is a token in the state, consume it
var token = $.bbq.getState('access_token');
$.bbq.pushState({}, 2)
} else if ($.bbq.getState('error')) {
} else {
doAuthRedirect();
}
/* HTML 5 geolocation. */
navigator.geolocation.getCurrentPosition(function(data) {
var lat = data['coords']['latitude'];
var lng = data['coords']['longitude'];
/* Create map. */
var map = new L.Map('map_canvas')
.setView(new L.LatLng(lat, lng), 15);
var mapboxUrl = 'http://a.tiles.mapbox.com/v3/[my Mapbox username].[my map id].jsonp';
wax.tilejson(mapboxUrl, function(tilejson) {
map.addLayer(new wax.leaf.connector(tilejson));
});
/* Query foursquare API for venue recommendations near the current location. */
$.getJSON(config.apiUrl + 'v2/venues/explore?ll=' + lat + ',' + lng + '&oauth_token=' + window.token, {}, function(data) {
venues = data['response']['groups'][0]['items'];
/* Place marker for each venue. */
for (var i = 0; i < venues.length; i++) {
/* Get marker's location */
var latLng = new L.LatLng(
venues[i]['venue']['location']['lat'],
venues[i]['venue']['location']['lng']
);
/* Build icon for each icon */
var leafletIcon = L.Icon.extend({
iconUrl: venues[i]['venue']['categories'][0]['icon'],
shadowUrl: null,
iconSize: new L.Point(32,32),
iconAnchor: new L.Point(16, 41),
popupAnchor: new L.Point(0, -51)
});
var icon = new leafletIcon();
var marker = new L.Marker(latLng, {icon: icon})
.bindPopup(venues[i]['venue']['name'], { closeButton: false })
.on('mouseover', function(e) { this.openPopup(); })
.on('mouseout', function(e) { this.closePopup(); });
map.addLayer(marker);
}
})
})
//]]>
</script>
</head>
<body>
<div style="width: 100%; height: 100%;" id="map_canvas"></div>
</body>
</html>
Cause of error: Callback uri is not valid for this consumer
A callback url is a webpage loaded after your web app has been verified. In this case, you need to specify a page for to send data to after authentication.
Double check your Foursquare credentials and update the callback uri to a valid link. The tutorial your shared uses https://developer.foursquare.com/docs/samples/explore, but you'll need to specify the url where this page is hosted.