hello there i have following code from google geoloction api..
this api is fetching an image of the current location of mine..
what i need to do is display these coordinates in google map(not in an image)
code is as follow:
function geoFindMe() {
var output = document.getElementById("out");
if (!navigator.geolocation) {
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
output.appendChild(img);
};
function error() {
output.innerHTML = "Unable to retrieve your location";
};
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, error);
}
your help will be appreciated !
Here is a Plunker to help you out! Just fill up the needed data on the iframe with yours and it will work. But instead of setting it to the img src you need to append it to the html.
Related
I am having trouble passing a value from a Google Spreadsheet to a Javascript function on the HTML.
code.gs
function getSiteCoords()
{
var emailA = Session.getActiveUser().getEmail();
var employeesheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Employees") // data pertaining to employees
var numRows=1;
while(employeesheet.getRange("A"+numRows+":A"+numRows).getValue() != "") //this will count the number of rows that are filled
{
if(employeesheet.getRange("A"+numRows).getValue()===emailA)
{
let coords = employeesheet.getRange("E"+numRows).getValue();
return coords;
}
numRows = numRows+1;
}
return "";
}
index.html
function checkPosition(position) {
console.log("Latitude: " + position.coords.latitude +
" Longitude: " + position.coords.longitude);
var lat= 54.978 ;
var long=-1.5622;
var coords = google.script.run.getSiteCoords();
console.log("Site Coords " + coords);
let calc= Math.sqrt(Math.pow(position.coords.latitude - lat , 2) + Math.pow(position.coords.longitude - long , 2));
console.log("calc: "+ calc);
if(calc>0.005)
window.location.replace("https://google.com");
}
No matter what, the coords on index.html returns undefined.
As you can see here, my app doesn't work when I try to use the variables "latitude" and "longitude" (those variables should get the user's current latitude and longitude) in the URL that I am getting JSON from.
Below is my code
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude
var longitude = position.coords.longitude
})
}
$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=" + latitude + "&lon=" + longitude, function(json){
var temp = json.main.temp
var ftemp = (temp * 1.8) + 32
var celsius = true
var condition = json.weather[0].main
var video;
switch (condition)
{
case "Clouds":
video = ""
break;
case "Rain":
video = "https://gcs-vimeo.akamaized.net/exp=1523487613~acl=%2A%2F401800757.mp4%2A~hmac=d66772ad9d6530ff1af68ac1dc01fcf17db42cce48ff72eebf97cc2b34ec0dab/vimeo-prod-skyfire-std-us/01/2146/5/135733055/401800757.mp4"
break;
case "Sunny":
video = ""
break;
}
$("#myVideo").html("<source src='" + video + "' type='video/mp4'>")
$("#condition").html(condition)
$("#number").html(Math.round(temp) + "°C")
$("#button").on("click", function(event){
event.preventDefault()
celsius = !celsius;
if (celsius)
{
$("#number").html(Math.round(temp) + "°C")
$("#button").html("(Switch to °F)")
}
else
{
$("#number").html(Math.round(ftemp) + "°F")
$("#button").html("(Switch to °C)")
}
})
})
But before I added the upper "if portion" and before I tried putting the variables into the URL, the app worked just fine, so the issue is somewhere in these few lines below.
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude
var longitude = position.coords.longitude
})
}
$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=" + latitude + "&lon=" + longitude, function(json){
Your variables are going out of scope:
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude
var longitude = position.coords.longitude
})
}
You need to declare the variables outside of that inner function:
var latitude, longitude;
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position) {
latitude = position.coords.latitude
longitude = position.coords.longitude
})
}
Oh, and you'll need to wait until you have gotten the coordinates, so you should wrap your getJSON call in a function, and then call it after you have the variables.
navigator.geolocation.getCurrentPosition(function(position) {
latitude = position.coords.latitude
longitude = position.coords.longitude
doAjaxRequest();
})
I'm working on simple App which provide for our clients our branches location, I use now a snapshot of the map, but I want to show the location on real map (Pan) not just an image.
I use Intel XDK platform (HTML/Javascribt)
This is the code I use:
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
var output = document.getElementById("mapp");
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=400x400&sensor=false";
output.appendChild(img);
};
output.innerHTML = "<p>Locating…</p>";
navigator.geolocation.getCurrentPosition(success, onError);
I found the answer, just by changing success function to:
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var bangalore = { lat: 12.97, lng: 77.59 };
var map = new google.maps.Map(document.getElementById('mapp'), {
zoom: 14,
center: bangalore
});
var beachMarker = new google.maps.Marker({
position: bangalore,
map: map,
});
I'm working on trying to trigger an event (to unhide an alert or image) based on gps coordinates falling within a certain range.
I think I need to do something like: If GPS Lat is > x (set based on location I want them to go to) and < y & GPS Long is > z and < a, then show (use js change css to display: block).
Am I down the right path? I'll post what I have as the basics of getting the GPS coordinates to just appear. I'm learning as I go here, so any help is appreciated for the proper structure. Thank you.
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
// device APIs are available
//
function onDeviceReady() {
var options = { timeout: 100000 };
watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
}
// onSuccess Geolocation
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
UPDATE:
I have gotten to the point where I'm not getting errors, now I'm hoping for some help to get a heading based on my current location and the destination. Any help is greatly appreciated. I'm posting my current code below:
document.addEventListener("deviceready", onDeviceReady, false);
var watchID = null;
var gpscoord = null;
var destLat = 37.200401
var destLon = 93.278610
function onDeviceReady() {
var gpsOptions = { timeout: 5000 };
gpscoord = navigator.geolocation.getCurrentPosition(gpsSuccess, gpsError, gpsOptions);
}
//gpsSuccess
//
function gpsSuccess(position) {
var lat = document.getElementById('latitude');
var lon = document.getElementById('longitude');
lat.innerHTML = 'Latitude:' + position.coords.latitude;
lon.innerHTML = 'Longitude:' + position.coords.longitude;
document.getElementById('gotoLat').innerHTML = 'Destination Latitude: ' + destLat;
document.getElementById('gotoLon').innerHTML = 'Destination Longitude: ' + destLon;
}
function gpsError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
<div class="container">
<br/>
<br/>
<p id="latitude">Watching latitude...</p>
<p id="longitude">Watching longitude...</p>
<br/>
<p id="gotoLat">Destination latitude...</p>
<p id="gotoLon">Destination longitude...</p>
</div>
Yeah that looks fine. The watcher will call onSuccess when the GPS has been successfully polled, and returns data.
I would save the Longitude and Latitude in the global scope, and then you can perform what ever kind of logic you want on it.
I am currently working on an application that periodically (every 30 secs) grabs two tweets within the UK from two specified football teams using the json format. Within the json file I can access the location of each tweet which is currently textual (manchester, bristol etc).
What I need to do is somehow geocode the locations and use the lat,lng co-ords to plot the tweet data onto multiple (2) infowindows. I've had a crack at using the geocode API but have had no luck yet. Currently I'm trying to just output the co-ords into a test div to see if it works, but it isn't.
My general code is below if that helps, any advice or help regarding this would be grrreat!
(currently I am also just outputting the twitter data into placeholder divs for the meantime)
//create urls for grabbing both teams tweets in the UK area
var url1="http://search.twitter.com/search.json?q=
%23"+team1+"&callback=?&geocode=53.779292%2C-1.579413%2C350mi";
var url2="http://search.twitter.com/search.json?q=
%23"+team2+"&callback=?&geocode=53.779292%2C-1.579413%2C350mi";
function team1tweets()
{
$.getJSON(
url1,function(results){ // get the tweets
var res1 = results.results[0].text;
var user1name = results.results[0].from_user;
var user1Location = results.results[0].location;
// get the first tweet in the response and place it inside the div
$("#last-tweet1").html(res1 + "<p>from: " + user1name + " (" +
user1Location + ")</p><p>");
}
);
//convert location into longitude and latitude
var convertLocUrl1 = "http://maps.googleapis.com/maps/api/geocode/
json?address=" + userLocation1 + "&sensor=false®ion=uk";
convertLocUrl1,function(locResult){
var lat1 = locResult.results[0].geometry.location.lat();
var lng1 = locResult.results[0].geometry.location.lng();
$("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</
p>");
}
}
function team2tweets()
{
$.getJSON(
url2,function(results){ // get the tweets
var res2 = results.results[0].text;
var user2name = results.results[0].from_user;
var user2Location = results.results[0].location;
$("#last-tweet2").html(res2 + "<p>from: " + user2name + " (" +
user2Location + ")</p>"); // get the first tweet in the response and
place it inside the div
});
//convert location into longitude and latitude
var convertLocUrl2 = "http://maps.googleapis.com/maps/api/geocode/
json?address=" + userLocation2 + "&sensor=false®ion=uk";
convertLocUrl2,function(locResult){
var lat2 = locResult.results[0].geometry.location.lat();
var lng2 = locResult.results[0].geometry.location.lng();
$("#testDiv2").html("latitude:" + lat2 + "<p>longitude:" + lng2 + "</
p>");
}
}
team1tweets();
team2tweets();
setInterval(checkStream1,20000);
setInterval(checkStream2,20000);
function checkStream1()
{
team1tweets();
}
function checkStream2()
{
team2tweets();
}
});
</script>
UPDATE: new code, using Google Maps API v3
<HTML>
<HEAD>
<TITLE>Tweet Ball</TITLE>
<LINK REL="Stylesheet" href="tweetBallStyles.css"></LINK>
<script src="https://maps-api-ssl.google.com/maps/api/js?v=3&sensor=false"
type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<!--GRABBING AND DISPLAYING TWEETS-->
<script type="text/javascript">
$(document).ready(function(){
var team1, team2;
//get team hashtag info
team1 = '<?php echo $_GET["team1"]; ?>';
team2 = '<?php echo $_GET["team2"]; ?>';
//create urls for grabbing both teams tweets in the UK area
var url1="http://search.twitter.com/search.json?q=%23"+team1+"&callback=?&geocode=53.779292%2C-1.579413%2C350mi";
var url2="http://search.twitter.com/search.json?q=%23"+team2+"&callback=?&geocode=53.779292%2C-1.579413%2C350mi";
var geocoder = new google.maps.Geocoder();
function team1tweets() {
$.getJSON(
url1, function(results) { // get the tweets
var res1 = results.results[0].text;
var user1name = results.results[0].from_user;
var user1Location = results.results[0].location;
// get the first tweet in the response and place it inside the div
$("#last-tweet1").html(res1 + "<p>from: " + user1name + " (" + user1Location + ")</p><p>");
//convert location into longitude and latitude
geocoder.geocode({
address: user1Location
}, function(locResult) {
console.log(locResult);
var lat1 = locResult[0].geometry.location.lat();
var lng1 = locResult[0].geometry.location.lng();
$("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>");
});
});
}
function team2tweets() {
$.getJSON(
url2, function(results) { // get the tweets
var res2 = results.results[0].text;
var user2name = results.results[0].from_user;
var user2Location = results.results[0].location;
// get the first tweet in the response and place it inside the div
$("#last-tweet2").html(res2 + "<p>from: " + user2name + " (" + user2Location + ")</p><p>");
//convert location into longitude and latitude
geocoder.geocode({
address: user2Location
}, function(locResult) {
console.log(locResult);
var lat2 = locResult[0].geometry.location.lat();
var lng2 = locResult[0].geometry.location.lng();
$("#testDiv2").html("latitude:" + lat2 + "<p>longitude:" + lng2 + "</p>");
});
});
}
team1tweets();
team2tweets();
//setInterval(checkStream1, 10000);
//setInterval(checkStream2, 10000);
function checkStream1() {
team1tweets();
}
function checkStream2() {
team2tweets();
}})
</script>
</HEAD>
<body>
<div id="container">
<div id="header"></div><!--end of header div-->
<div id="mainContent">
<ul>
<li><a href="index.php">return to team select</li>
</ul>
<div id="testDiv"></div>
<div id="testDiv2"></div>
<div id="map_canvas"></div>
<div id="last-tweet1-container">
<div id="last-tweet1">
</div>
</div>
<div id="last-tweet2-container">
<div id="last-tweet2">
</div>
</div>
<div id="footer">
</div>
</div><!--end of mainContent div-->
</div><!--end of container div-->
</BODY>
</HTML>
Here is the JSFiddle Demo: using Google Map V3 API's Geocode to get the lat and lng of your locations:
I am able to modify your code to the following without error. Basically, you have to call the Google Map Geocode within your first getJSON, because user1Location is retrived async and thus undefined when accessed outside of your twitter json callback. AFAIK, Google Geocode VIA HTTP does not allow JSONP, and thus, retriving HTTP through JavaScript VIA Ajax is a violation of cross-domain policy. Another alternative is to use the Google Map API V3's Geocoding or you can use server side to retrive the HTTP JSON.
function team1tweets() {
$.getJSON(
url1, function(results) { // get the tweets
var res1 = results.results[0].text;
var user1name = results.results[0].from_user;
var user1Location = results.results[0].location;
// get the first tweet in the response and place it inside the div
$("#last-tweet1").html(res1 + "<p>from: " + user1name + " (" + user1Location + ")</p><p>");
//convert location into longitude and latitude
var convertLocUrl1 = "http://maps.googleapis.com/maps/api/geocode/json?address=" + user1Location + "&sensor=false®ion=uk";
$.getJSON(convertLocUrl1,function(locResult) {
var lat1 = locResult.results[0].geometry.location.lat();
var lng1 = locResult.results[0].geometry.location.lng();
$("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>");
});
});
}
UPDATE:
Here is the Google Map API V3 way of getting LatLng of the locations you wish. Apply similar code to your team2tweets(). I basically replace your $.getJSON with google.map.Geocode:
function team1tweets() {
$.getJSON(
url1, function(results) { // get the tweets
var res1 = results.results[0].text;
var user1name = results.results[0].from_user;
var user1Location = results.results[0].location;
// get the first tweet in the response and place it inside the div
$("#last-tweet1").html(res1 + "<p>from: " + user1name + " (" + user1Location + ")</p><p>");
//convert location into longitude and latitude
geocoder.geocode({
address: user1Location
}, function(locResult) {
console.log(locResult);
var lat1 = locResult[0].geometry.location.lat();
var lng1 = locResult[0].geometry.location.lng();
$("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>");
});
});
}