Struggling with Google Maps geocoding API - javascript

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&region=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&region=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&region=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>");
});
});
}

Related

New line JavaScript

<!DOCTYPE html>
<html>
<head>
<title> Location Test </title>
<link rel="shortcut icon" href="#">
</head>
<body>
<h1> Location </h1>
<label id = "Address"> </label>
<br>
<input type="button" value="Log Out" id="LogOut">
<script>
const logoutButton = document.getElementById("LogOut");
function getLocation() {
navigator.geolocation.getCurrentPosition(
function(Position) {
var currentdate = new Date();
document.getElementById("Address").innerHTML = document.getElementById("Address").textContent + "Last Sync: " + currentdate.getDate() + "/" +
(currentdate.getMonth() + 1) + "/" +
currentdate.getFullYear() + ". " +
currentdate.getHours() + ":" +
currentdate.getMinutes() + "." +
currentdate.getSeconds() + ". ";
document.getElementById("Address").innerHTML = document.getElementById("Address").textContent + "Latitude: " + Position.coords.latitude;
document.getElementById("Address").innerHTML = document.getElementById("Address").textContent + " Longitude: " + Position.coords.longitude;
document.getElementById("Address").innerHTML = document.getElementById("Address").textContent + " Accuracy: " + Position.coords.accuracy;
document.getElementById("Address").innerHTML = document.getElementById("Address").textContent + " Heading towards direction: " + Position.coords.heading;
document.getElementById("Address").innerHTML = document.getElementById("Address").textContent + " Speed: " + Position.coords.speed;
var api_key = '206170168bcf4fdf905d85a34f7b3d79';
var latitude = Position.coords.latitude;
var longitude = Position.coords.longitude;
var api_url = 'https://api.opencagedata.com/geocode/v1/json'
var request_url = api_url +
'?' +
'key=' + api_key +
'&q=' + encodeURIComponent(latitude + ',' + longitude) +
'&pretty=1' +
'&no_annotations=1';
var request = new XMLHttpRequest();
request.open('GET', request_url, true);
request.onload = function() {
if (request.status === 200) {
// Success!
var data = JSON.parse(request.responseText);
document.getElementById("Address").innerHTML = document.getElementById("Address").textContent + " Address: " + data.results[0].formatted; // print the location
} else if (request.status <= 500) {
// We reached our target server, but it returned an error
console.log("unable to geocode! Response code: " + request.status);
var data = JSON.parse(request.responseText);
console.log('error msg: ' + data.status.message);
} else {
console.log("server error");
}
};
request.onerror = function() {
console.log("unable to connect to server");
};
request.send(); // make the request
},
function(PositionError) {
document.getElementById("Latitude").innerHTML = "Could not get latitude";
document.getElementById("Longitude").innerHTML = "Could not get longitude";
})
}
getLocation();
setInterval(getLocation, 1000 * 60 * 5)
logoutButton.addEventListener("click", (e) => {
e.preventDefault();
window.location.href = "login.html";
})
</script>
</body>
</html>
So basically, what I want to do is create a new line at the end of the function. So each time I use setInterval, it creates a new line in the label. But I'm not sure how to. That way, every time it updates the location after 5 minutes, it prints it on a new line.
You can ignore the rest of what I say, I'm getting the error that my post is mostly code.
Just write a <br> tag. So change
+ " Address: "
to:
+ "<br> Address: "
As trincot stated, the inclusion of the <br> (line break) tag is the way to go as we want to create new lines directly in the address label. However, a code change is required because our newly appended line breaks will get rewritten when we re-call function getLocation().
Appended line breaks will vanish if we reinitialise our label's innerHTML with its previous textContent because textContent selects the message from the target and ignores nested HTML contents.
Thus, the best solution is to formulate the location before its inclusion to the address label.
// Get local date and time.
var currentdate = new Date();
var cd_date = currentdate.toLocaleDateString("en-UK");
var cd_time = currentdate.toLocaleTimeString("en-UK");
// Formulate location string.
var location = `
Last Sync: ${cd_date} - ${cd_time},
Latitude: ${Position.coords.latitude},
Longitude: ${Position.coords.longitude},
Accuracy: ${Position.coords.accuracy},
Heading towards direction: ${Position.coords.heading},
Speed: ${Position.coords.speed},
`.replace(/\s{2}/g, '').trim(); // Remove additional spaces.
...
if (request.status === 200) {
// Success!
var data = JSON.parse(request.responseText);
location += ` Address: "${data.results[0].formatted}".`;
// print the location
var elm_address = document.getElementById("Address");
elm_address.innerHTML += (elm_address.innerHTML.trim().length > 0) ? `<br>${location}` : location;
}
We want to include line breaks when we append additional location to the address label, so I decided to have a conditional statement before appending stage.
elm_address.innerHTML += will append the location after
following condition (elm_address.innerHTML.trim().length > 0).
The condition checks if address label is empty.
? `<br>${location}` : location;
When the condition's result is negative, location is appended without a line break. Otherwise, a line break is included.

Passing Google Spreadsheet value from Google Apps script to HTML returns undefined

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.

Weather API not working

Why am i not getting any data back from the weather api i am trying to update the html tag to show the temperature please help
$(document).ready(function() {
var loc = [];
console.log(loc);
$.getJSON("https://ipinfo.io?token=97f4f0d67b28dc", function(response) {
loc = response.loc.split(",");
document.getElementById("Location").innerHTML =
response.city + "," + response.country;
});
$.getJSON(
"https://fcc-weather-api.glitch.me/api/current?lat=" +
loc[0] +
"&lon=" +
loc[1],
function(data) {
console.log(data);
document.getElementById("Temperature").innerHTML = data.main.temp;
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
It's because when you are calling the second request, the first isn't finished yet, so the lat long values are undefined.
You need to put your second request inside first like this:
$(document).ready(function() {
var loc = [];
$.getJSON("https://ipinfo.io?token=97f4f0d67b28dc", function(response) {
loc = response.loc.split(",");
console.log(Number(loc[0]));
document.getElementById("Location").innerHTML =
response.city + "," + response.country;
$.getJSON(
"https://fcc-weather-api.glitch.me/api/current?lat=" +
loc[0] +
"&lon=" +
loc[1],
function(data) {
console.log(data);
document.getElementById("Temperature").innerHTML = data.main.temp;
}
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Location"></div>
<div id="Temperature"></div>

google map current location preview

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.

how to make a clickable phone number in iphone application by using javascript and html5 applied mysql database?

and I know that 1-801-555-1212 will make this certain number be clickable. I tested it and it works fine.
My question is if I do have a variable phone which will call from database via mysql, how can I make this variable be clickable? I've tried a lot of way but none of them work.
I used the following link to create a store locator page
http://code.google.com/apis/maps/articles/phpsqlsearch.html
and my original code is here.
<!DOCTYPE html>
Store Locate
<script src="http://maps.google.com/maps?file=api&v=2&sensor=true&key=ABQIAAAAtwc3xGzBndDAUOSllG2AkxTnNPa_SyQGEldLwhmK8Cfx_H4lPRTZuzWKU2EDVO1MyUD3Ym_0fNuEiw" type="text/javascript"></script>
<script src="jquery-1.5.2.min.js"></script>
<script>
// One-shot position request.
navigator.geolocation.getCurrentPosition(showMap);
function showMap(position) {
// Show a map centered at (position.coords.latitude, position.coords.longitude).
}
map.setCenter(new google.maps.LatLng(position.coords.latitude,
position.coords.longitude), 13);
<script type="text/javascript">
//<![CDATA[
var map;
var geocoder;
function load() {
if (GBrowserIsCompatible()) {
geocoder = new GClientGeocoder();
map = new GMap2(document.getElementById('map'));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(40, -100), 4);
}
}
function searchLocations() {
var address = document.getElementById('addressInput').value;
geocoder.getLatLng(address, function(latlng) {
if (!latlng) {
alert(address + ' not found');
} else {
searchLocationsNear(latlng);
}
});
}
function searchLocationsNear(center) {
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
GDownloadUrl(searchUrl, function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName('marker');
map.clearOverlays();
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = '';
if (markers.length == 0) {
sidebar.innerHTML = 'No results found.';
map.setCenter(new GLatLng(40, -100), 4);
return;
}
var bounds = new GLatLngBounds();
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute('name');
var address = markers[i].getAttribute('address');
var distance = parseFloat(markers[i].getAttribute('distance'));
var phone = markers[i].getAttribute('phone');
var url = markers[i].getAttribute('url');
var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
parseFloat(markers[i].getAttribute('lng')));
var marker = createMarker(point, name, address, phone, url);
map.addOverlay(marker);
var sidebarEntry = createSidebarEntry(marker, name, address, distance, phone, url);
sidebar.appendChild(sidebarEntry);
bounds.extend(point);
}
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
});
}
function createMarker(point, name, address, phone, url) {
var marker = new GMarker(point);
var html = '<b>' + name + '</b> <br/>' + address + '</b> <br/>' + phone + '</b> <br/>' + url + '</b> <br/>'
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
function createSidebarEntry(marker, name, address, distance, phone, url) {
var div = document.createElement('div');
var html = '<b>' + name + '</b> (' + distance.toFixed(1) + ')<br/>' + address + '</b> <br/>' + phone + '</b> <br/>' + url;
div.innerHTML = html;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
GEvent.addDomListener(div, 'click', function() {
GEvent.trigger(marker, 'click');
});
GEvent.addDomListener(div, 'mouseover', function() {
div.style.backgroundColor = '#eee';
});
GEvent.addDomListener(div, 'mouseout', function() {
div.style.backgroundColor = '#fff';
});
return div;
}
//]]>
</script>
I add a variable phone which will call from mysql. and my question is how can I make it clickable?...I tried to modify following code in many ways
function createSidebarEntry(marker, name, address, distance, phone, url) {
var div = document.createElement('div');
var html = '<b>' + name + '</b> (' + distance.toFixed(1) + ')<br/>' + address + '</b> <br/>' + phone + '</b> <br/>' + url;
but I always just got code error.
anyone can help me??
thanks
You can surround the phone number by a "a" tag with a href="tel:{PHONE NUMBER}"
How to mark-up phone numbers?

Categories