I am trying to get the location of user via Geolocation API, it was working fine till yesterday but today i am getting as "Unable to get Location" for every attempt
Script used for API is
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//var num = parseFloat(lat);
//var str = num.toFixed(10);
//str = str.substring(0, str.length-7);
$('#yourlat').val(lat);$('#yourlat1').val(lat);
//var num1 = parseFloat(lng);
//var str1 = num1.toFixed(10);
//str1 = str1.substring(0, str1.length-7);
$('#yourlong').val(lng);$('#yourlong1').val(lng);
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
var addressget ='';
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
//alert(results[0].formatted_address)
addressget = results[0].formatted_address;
$('#yourcity').html(addressget);
$('#yourcitys').val(addressget);
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//city data
var stateget ='';
stateget = city.short_name + " " + city.long_name;
$('#yourstate').html(stateget);
}
else {
alert("We are not able to get your location..");
}
}
else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
I am calling function on bodyload
<body onload="initialize()">
Everytime i allow to get location it gives error as We are not able to get your location..
I would suggest checking what the status variable is indicating. the valuesfor the class google.maps.GeocoderStatus can be found from the API documentation
Related
var Twit = require('twit');
var replie = ['1','2','3'];
var T = new Twit({
....
})
var stream = T.stream('statuses/filter', { track: '#beykant_' });
stream.on('tweet',tweetEvent);
function tweetEvent(eventMsg) {
var replyto = eventMsg.in_reply_to_screen_name;
var text = eventMsg.text;
var from = eventMsg.user.screen_name;
if(replyto == 'beykant_'){
var newTweet = '#' + from + replie[Math.floor(Math.random() * replie.length)];
tuit(newTweet);
}
}
function tuit(txt){
var tweet = {
status: txt
}
T.post('statuses/update',tweet, tweeted);
function tweeted (err, data, response) {
if(err){
console.log('err');
}else{
console.log('ready')
}
console.log(data)
}
}
I used twitter-api-v2, I couldn't find the response event when #mentioned on it. When I tried the twit module, it gave such an error again, can anyone show a solution, it would be better if it can be done with the twitter-api-v2 module, thank you.
Im trying to get the Messages from a Youtube Livestream, works, but i dont get new Messages. The NextPageToken is included.
Sometimes i get new messages, but it takes arround 5-10min.
Youtube Chat Sending works also fine.
Any Idea?
This is from the Docs: https://developers.google.com/youtube/v3/live/docs/liveChatMessages/list
private async Task GetMessagesAsync(string liveChatId, string nextPageToken, long? pollingIntervalMillis)
{
liveChatId = "EiEKGFVDVUQ3WGNXTk92SlpvaHFMM3dZTi1uZxIFL2xpdmU";
if (!updatingChat)
{
if (!string.IsNullOrEmpty(liveChatId))
{
newMessages = true;
var chatMessages = youTubeService.LiveChatMessages.List(liveChatId, "id,snippet,authorDetails");
var chatResponse = await chatMessages.ExecuteAsync();
PageInfo pageInfo = chatResponse.PageInfo;
newMessages = false;
if (pageInfo.TotalResults.HasValue)
{
if (!prevCount.Equals(pageInfo.TotalResults.Value))
{
prevCount = pageInfo.TotalResults.Value;
newMessages = true;
}
}
if (newMessages)
{
Messages = new List<YouTubeMessage>();
foreach (var chatMessage in chatResponse.Items)
{
string messageId = chatMessage.Id;
string displayName = chatMessage.AuthorDetails.DisplayName;
string displayMessage = chatMessage.Snippet.DisplayMessage;
string NextPagetoken = chatResponse.NextPageToken;
YouTubeMessage message = new YouTubeMessage(messageId, displayName, displayMessage);
if (!Messages.Contains(message))
{
Messages.Add(message);
string output = "[" + displayName + "]: " + displayMessage;
Console.WriteLine(time + output);
}
}
}
await GetMessagesAsync(liveChatId, chatResponse.NextPageToken, chatResponse.PollingIntervalMillis);
}
}
updatingChat = false;
await Task.Delay(100);
}
public async Task YouTubeChatSend(string message)
{
try
{
LiveChatMessage liveMessage = new LiveChatMessage();
liveMessage.Snippet = new LiveChatMessageSnippet()
{
LiveChatId = "EiEKGFVDVUQ3WGNXTk92SlpvaHFMM3dZTi1uZxIFL2xpdmU",
Type = "textMessageEvent",
TextMessageDetails = new LiveChatTextMessageDetails() { MessageText = message }
};
var insert = this.youTubeService.LiveChatMessages.Insert(liveMessage, "snippet");
var response = await insert.ExecuteAsync();
if (response != null)
{
}
}
catch
{
Console.WriteLine("Failed to chat send");
}
}
I have got following script in Google docs spreadsheet which is fetching data from Fitbit. Script worked fine so far but recently on 6th July Google stopped using OAuthConfig so script is not working since:-(
I am not programmer, I am just advanced user. So I would like to kindly ask some programmer to help tune script below in order to make it work again.
// Key of ScriptProperty for Firtbit consumer key.
var CONSUMER_KEY_PROPERTY_NAME = "fitbitConsumerKey";
// Key of ScriptProperty for Fitbit consumer secret.
var CONSUMER_SECRET_PROPERTY_NAME = "fitbitConsumerSecret";
// Default loggable resources (from Fitbit API docs).
var LOGGABLES = ["activities/log/steps", "activities/log/distance",
"activities/log/activeScore", "activities/log/activityCalories",
"activities/log/calories", "foods/log/caloriesIn",
"activities/log/minutesSedentary",
"activities/log/minutesLightlyActive",
"activities/log/minutesFairlyActive",
"activities/log/minutesVeryActive", "sleep/timeInBed",
"sleep/minutesAsleep", "sleep/minutesAwake", "sleep/awakeningsCount",
"body/weight", "body/bmi", "body/fat",];
// function authorize() makes a call to the Fitbit API to fetch the user profile
function authorize() {
var oAuthConfig = UrlFetchApp.addOAuthService("fitbit");
oAuthConfig.setAccessTokenUrl("https://api.fitbit.com/oauth/access_token");
oAuthConfig.setRequestTokenUrl("https://api.fitbit.com/oauth/request_token");
oAuthConfig.setAuthorizationUrl("https://api.fitbit.com/oauth/authorize");
oAuthConfig.setConsumerKey(getConsumerKey());
oAuthConfig.setConsumerSecret(getConsumerSecret());
var options = {
"oAuthServiceName": "fitbit",
"oAuthUseToken": "always",
};
// get the profile to force authentication
Logger.log("Function authorize() is attempting a fetch...");
try {
var result = UrlFetchApp.fetch("https://api.fitbit.com/1/user/-/profile.json", options);
var o = Utilities.jsonParse(result.getContentText());
return o.user;
}
catch (exception) {
Logger.log(exception);
Browser.msgBox("Error attempting authorization");
return null;
}
}
// function setup accepts and stores the Consumer Key, Consumer Secret, firstDate, and list of Data Elements
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setTitle("Setup Fitbit Download");
app.setStyleAttribute("padding", "10px");
var consumerKeyLabel = app.createLabel("Fitbit OAuth Consumer Key:*");
var consumerKey = app.createTextBox();
consumerKey.setName("consumerKey");
consumerKey.setWidth("100%");
consumerKey.setText(getConsumerKey());
var consumerSecretLabel = app.createLabel("Fitbit OAuth Consumer Secret:*");
var consumerSecret = app.createTextBox();
consumerSecret.setName("consumerSecret");
consumerSecret.setWidth("100%");
consumerSecret.setText(getConsumerSecret());
var firstDate = app.createTextBox().setId("firstDate").setName("firstDate");
firstDate.setName("firstDate");
firstDate.setWidth("100%");
firstDate.setText(getFirstDate());
// add listbox to select data elements
var loggables = app.createListBox(true).setId("loggables").setName(
"loggables");
loggables.setVisibleItemCount(4);
// add all possible elements (in array LOGGABLES)
var logIndex = 0;
for (var resource in LOGGABLES) {
loggables.addItem(LOGGABLES[resource]);
// check if this resource is in the getLoggables list
if (getLoggables().indexOf(LOGGABLES[resource]) > -1) {
// if so, pre-select it
loggables.setItemSelected(logIndex, true);
}
logIndex++;
}
// create the save handler and button
var saveHandler = app.createServerClickHandler("saveSetup");
var saveButton = app.createButton("Save Setup", saveHandler);
// put the controls in a grid
var listPanel = app.createGrid(6, 3);
listPanel.setWidget(1, 0, consumerKeyLabel);
listPanel.setWidget(1, 1, consumerKey);
listPanel.setWidget(2, 0, consumerSecretLabel);
listPanel.setWidget(2, 1, consumerSecret);
listPanel.setWidget(3, 0, app.createLabel(" * (obtain these at dev.fitbit.com)"));
listPanel.setWidget(4, 0, app.createLabel("Start Date for download (yyyy-mm-dd)"));
listPanel.setWidget(4, 1, firstDate);
listPanel.setWidget(5, 0, app.createLabel("Data Elements to download:"));
listPanel.setWidget(5, 1, loggables);
// Ensure that all controls in the grid are handled
saveHandler.addCallbackElement(listPanel);
// Build a FlowPanel, adding the grid and the save button
var dialogPanel = app.createFlowPanel();
dialogPanel.add(listPanel);
dialogPanel.add(saveButton);
app.add(dialogPanel);
doc.show(app);
}
// function sync() is called to download all desired data from Fitbit API to the spreadsheet
function sync() {
// if the user has never performed setup, do it now
if (!isConfigured()) {
setup();
return;
}
var user = authorize();
// Spatny kod, oprava nize - var doc = SpreadsheetApp.getActiveSpreadsheet();
var doc = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Pavel');
doc.setFrozenRows(1);
var options = {
"oAuthServiceName": "fitbit",
"oAuthUseToken": "always",
"method": "GET"
};
// prepare and format today's date, and a list of desired data elements
var dateString = formatToday();
var activities = getLoggables();
// for each data element, fetch a list beginning from the firstDate, ending with today
for (var activity in activities) {
var currentActivity = activities[activity];
try {
var result = UrlFetchApp.fetch("https://api.fitbit.com/1/user/-/"
+ currentActivity + "/date/" + getFirstDate() + "/"
+ dateString + ".json", options);
} catch (exception) {
Logger.log(exception);
Browser.msgBox("Error downloading " + currentActivity);
}
var o = Utilities.jsonParse(result.getContentText());
// set title
var titleCell = doc.getRange("a1");
titleCell.setValue("date");
var cell = doc.getRange('a2');
// fill the spreadsheet with the data
var index = 0;
for (var i in o) {
// set title for this column
var title = i.substring(i.lastIndexOf('-') + 1);
titleCell.offset(0, 1 + activity * 1.0).setValue(title);
var row = o[i];
for (var j in row) {
var val = row[j];
cell.offset(index, 0).setValue(val["dateTime"]);
// set the date index
cell.offset(index, 1 + activity * 1.0).setValue(val["value"]);
// set the value index index
index++;
}
}
}
}
function isConfigured() {
return getConsumerKey() != "" && getConsumerSecret() != "";
}
function setConsumerKey(key) {
ScriptProperties.setProperty(CONSUMER_KEY_PROPERTY_NAME, key);
}
function getConsumerKey() {
var key = ScriptProperties.getProperty(CONSUMER_KEY_PROPERTY_NAME);
if (key == null) {
key = "";
}
return key;
}
function setLoggables(loggable) {
ScriptProperties.setProperty("loggables", loggable);
}
function getLoggables() {
var loggable = ScriptProperties.getProperty("loggables");
if (loggable == null) {
loggable = LOGGABLES;
} else {
loggable = loggable.split(',');
}
return loggable;
}
function setFirstDate(firstDate) {
ScriptProperties.setProperty("firstDate", firstDate);
}
function getFirstDate() {
var firstDate = ScriptProperties.getProperty("firstDate");
if (firstDate == null) {
firstDate = "2012-01-01";
}
return firstDate;
}
function formatToday() {
var todayDate = new Date;
return todayDate.getFullYear()
+ '-'
+ ("00" + (todayDate.getMonth() + 1)).slice(-2)
+ '-'
+ ("00" + todayDate.getDate()).slice(-2);
}
function setConsumerSecret(secret) {
ScriptProperties.setProperty(CONSUMER_SECRET_PROPERTY_NAME, secret);
}
function getConsumerSecret() {
var secret = ScriptProperties.getProperty(CONSUMER_SECRET_PROPERTY_NAME);
if (secret == null) {
secret = "";
}
return secret;
}
// function saveSetup saves the setup params from the UI
function saveSetup(e) {
setConsumerKey(e.parameter.consumerKey);
setConsumerSecret(e.parameter.consumerSecret);
setLoggables(e.parameter.loggables);
setFirstDate(e.parameter.firstDate);
var app = UiApp.getActiveApplication();
app.close();
return app;
}
// function onOpen is called when the spreadsheet is opened; adds the Fitbit menu
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [{
name: "Sync",
functionName: "sync"
}, {
name: "Setup",
functionName: "setup"
}, {
name: "Authorize",
functionName: "authorize"
}];
ss.addMenu("Fitbit", menuEntries);
}
// function onInstall is called when the script is installed (obsolete?)
function onInstall() {
onOpen();
}
Problem solved with updated code at https://github.com/loghound/Fitbit-for-Google-App-Script
I'm trying to use the execute locally feature in breeze and it's giving me the error 'undefined is not a function'. Following is the two functions - in first one, I retrieve the data from the database and in the second one I try to get the data from the local cache.
function getServices(clientId, currentLocation, activeStatus) {
var self = this;
var Predicate = breeze.Predicate;
var whereClause = Predicate.create("activeStatus", "==", parseInt(activeStatus));
return EntityQuery.from('Services')
.withParameters({ clientId: clientId, currentLocation: currentLocation })
.where(whereClause)
.expand("Location")
.using(self.manager)
.execute()
.then(querySucceeded, this._queryFailed);
function querySucceeded(data) {
if (data.results.length > 0) {
services = data.results;
}
logSuccess(localize.getLocalizedString('_RetrievedHolidays_'), services, true);
return services;
}
}
function getServicesLocally(clientId, currentLocation, activeStatus, category, type, includeSubLocations) {
var self = this;
services = [];
var Predicate = breeze.Predicate;
var p1 = Predicate.create("activeStatus", "==", parseInt(activeStatus));
var p2 = Predicate.create("fkServiceTypeId", "==", parseInt(type));
var p3 = Predicate.create("fkServiceCategoryId", "==", parseInt(category));
var whereClause = p1;
if (type != 0)
whereClause = whereClause.and(p2);
if (category != 0)
whereClause = whereClause.and(p3);
return EntityQuery.from('Services')
.withParameters({ clientId: clientId, currentLocation: currentLocation })
.where(whereClause)
.orderBy('location.fkLocationTypeId')
.using(self.manager)
.executeLocally()
.then(querySucceeded, this._queryFailed);
function querySucceeded(data) {
if (data.results.length > 0) {
services = data.results;
//if sub-locations are to be ommitted, remove the services of the sub-locations
if (!includeSubLocations) {
services = removeServicesOfSubLocationsFromServiceList(services);
}
}
logSuccess(localize.getLocalizedString('_RetrievedHolidays_'), services, true);
return services;
}
}
Following is the API call that retrieve the services:
[HttpGet]
public IQueryable Services(int clientId, int currentLocation)
{
locationsRepo = new ClientLocationsRepository(this.CurrentUser, this.SystemContextProvider, clientId);
serviceRepo = new ClientServiceRepository(this.CurrentUser, this.SystemContextProvider, clientId);
int currentLocationType = locationsRepo.GetLocationType(currentLocation).LocationTypeId;
List<Location> accessibleLocationList = GetLocationsAccessible(clientId, currentLocation).ToList();
IQueryable productsAndServices = serviceRepo.GetProductsAndServices(accessibleLocationList, currentLocationType);
return productsAndServices;
}
because the method you are using to query cache locally is giving the error "undefined is not a function".Use this method while querying cache locally
manager.executeQuery(query).then(function(data) {
var query2 = query.where(predicate)
.using(breeze.FetchStrategy.FromLocalCache);
manager.executeQuery(query2).then(function(dataSubset) {
// use your datasubset to populate your results....
});
I know there are a few topics on this, but I seem to be fumbling my way through with no results. I'm trying to use a controller to return JSON results to my Bing Maps functions.
Here's what I have for my controller (yes it is properly returning JSON data.
Function Regions() As JsonResult
Dim rj As New List(Of RtnJson)()
rj.Add(New RtnJson("135 Bow Meadows Drive, Cochrane, Alberta", "desc", "title"))
rj.Add(New RtnJson("12 Bowridge Dr NW, Calgary, Alberta, Canada", "desc2", "title2"))
Return Json(rj, JsonRequestBehavior.AllowGet)
End Function
Then in my script I have this, but it's not working.
<script type="text/javascript">
var map = null;
var centerLat = 51.045 ;
var centerLon = -114.05722;
var path = "<%: Url.Action("GetRegions", "Regions")%>";
function LoadMap() {
map = new VEMap('bingMap');
map.LoadMap(new VELatLong(centerLat, centerLon), 10);
$.getJSON(path, function(json){
$.each(json, function(){
alert(this.address); // the alert message is "undefined"
StartGeocoding(this.address, this.title, this.description);
});
});
}
function StartGeocoding(address, title, desc) {
map.Find(null, // what
address, // where
null, // VEFindType (always VEFindType.Businesses)
null, // VEShapeLayer (base by default)
null, // start index for results (0 by default)
null, // max number of results (default is 10)
null, // show results? (default is true)
null, // create pushpin for what results? (ignored since what is null)
true, // use default disambiguation? (default is true)
false, // set best map view? (default is true)
GeocodeCallback); // call back function
}
function GeocodeCallback(shapeLayer, findResults, places, moreResults, errorMsg) {
var bestPlace = places[0];
// Add pushpin to the *best* place
var location = bestPlace.LatLong;
var newShape = new VEShape(VEShapeType.Pushpin, location);
var desc = "Latitude: " + location.Latitude + "<br>Longitude:" + location.Longitude;
newShape.SetDescription(desc);
newShape.SetTitle(bestPlace.Name);
map.AddShape(newShape);
}
$(document).ready(function () {
LoadMap();
});
</script>
Well damn.
Turns out that I was using this.address when I should have been using this.Address. Can't believe I missed that.