get city name from longitude and latitude using google geocoding api jquery - geocoding

I want to get city name from longitude and latitude.
I am using following code but it is returning the entire address with city name, postal code, province and country.
I just want only city name.
$.ajax({ url:'http://maps.googleapis.com/maps/api/geocode/json?latlng='+position.coords.latitude+','+position.coords.longitude+'&sensor=true',
success: function(data){
alert(data.results[4].formatted_address);
}
});
Please see the result from geocoding
{
"long_name" : "Vancouver",
"short_name" : "Vancouver",
"types" : [ "locality", "political" ]
},

formatted_address is always going to return you a full address string, due to the nature of the datatype from the API. You need to directly reference the locality type in the address_components array.
Google Maps Geocoding API
So for example, you need to search through the returned address_components array for the locality type:
for (var i = 0; i < data.results[4].address_components.length; i++) {
for (var j = 0; j < data.results[4].address_components[i].types.length; j++) {
if(data.results[4].address_components[i].types[j] == 'locality') {
var city_name = data.results[4].address_components[i].long_name;
alert(city_name);
}
}
}

I ran into an issue where not all localities are in results[4] so I looped through all.
url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true";
$.ajax(url).done(function(data) {
for (var i = 0; i < data.results.length; i++) {
for (var j = 0; j < data.results[i].address_components.length; j++) {
for (var k = 0; k < data.results[i].address_components[j].types.length; k++) {
if (data.results[i].address_components[j].types[k] === 'locality') {
var city_name = data.results[i].address_components[j].long_name;
}
}
}
}
}
NOTE: This is also using update jQuery AJAX syntax since the original post..

You need to check some variables to ensure that code will work for every positions, even if locality/city is not present:
var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&sensor=false'
$.ajax({
dataType: "json",
url: url,
async: false,
scriptCharset: "utf-8",
contentType: "application/json; charset=utf-8",
success: function(json)
{
var found_city = false;
if (json && json.results.length > 0)
{
for (var k=0; k < json.results.length; k++ ) {
if (json.results[k].address_components) {
for (var i = 0; i < json.results[k].address_components.length; i++) {
if (json.results[k].address_components[i]) {
for (var j = 0; j < json.results[k].address_components[i].types.length; j++) {
if(json.results[k].address_components[i].types[j] == 'locality') {
var city_name = json.results[k].address_components[i].long_name;
alert(city_name);
found_city = true
}
}
}
}
}
}
}
if (!found_city) {
alert("City not found!");
}
}
})
.fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
alert("Request Failed: " + err );
});

Related

Aspose Cells. Get rows by group

How can I read rows by group using Aspose?
example
See the following sample code using Aspose.Cells for your reference:
e.g.
Sample code:
//Loading the file
Workbook book = new Workbook("e:\\test2\\Bk_readgrouped.xlsx");
//Get the first worksheet in the workbook
Worksheet sheet = book.Worksheets[0];
int maxRow = sheet.Cells.MaxDataRow;
int maxCol = sheet.Cells.MaxDataColumn;
int chk = 0;
bool pname = false;
Console.WriteLine("Retrieving each group's data");
for (int i = 0; i <= maxRow; i++)
{
int rowOutlineLevel = sheet.Cells.GetGroupedRowOutlineLevel(i);
if (rowOutlineLevel > 0)
{
pname = true;
if (pname== true & chk != rowOutlineLevel)
{
Console.WriteLine("\n");
Console.WriteLine("Group:" + rowOutlineLevel);
pname = false;
chk = rowOutlineLevel;
}
for (int j = 0; j <= maxCol; j++)
{
Console.Write(sheet.Cells[i, j].StringValue + "\t");
}
Console.WriteLine();
}
}
Hope, this helps a bit.
PS. I am working as Support developer/ Evangelist at Aspose.
This works for me:
public virtual void ProcessExcelSheetTree (Worksheet Excelsheet, int current_level)
{
int current_row = 1;
int maxRow = Excelsheet.Cells.MaxDataRow;
int firstGroupIndex = 0;
while(Excelsheet.Cells[current_row, 0].StringValue != "")
{
var currentRow = Excelsheet.Cells.Rows[current_row];
if(currentRow.GroupLevel == current_level)
{
string targetName = Excelsheet.Cells[current_row, 0].StringValue;
Console.WriteLine(targetName);
firstGroupIndex = currentRow.Index;
for (int i = firstGroupIndex + 1; i <= maxRow; i++)
{
if(Excelsheet.Cells.Rows[i].GroupLevel > current_level)
{
string subTargetName = Excelsheet.Cells[i, 0].StringValue;
Console.WriteLine(" - " + subTargetName);
}
else
{
break;
}
}
}
current_row++;
}
}

Detect consecutive objects with a common attribute in 2-D array

I have a 2-D array of gems, all the gems have been given random color. Now i want to detect if three or more consecutive gems in a row or column has the same color. If so i want to do some action with those gems.
Gem gems[10][10];
for(int i=0;i<10;++i){
for(int j=0;j<10;++j){
gems[i][j].setColor(GetRandInRange(0,6));
}
}
bool detectMatch(){
for(int i=0;i<10;++i){
for(int j=0;j<10;++j){
// Code to detect three or more consecutive gems with same color
// Give some special color to the matched gems
}
}
Here is how i tried but it doesn't work
bool GameBoard::findMatch(){
for(int i=0;i<10;++i){
int count=0;
for(int j=0;j<10;++j){
if(j!=0){
if(gems[i][j].getColor()==gems[i][j-1].getColor()){ //Color same with previous one
int a=i, b=j;
while(gems[a][b].getColor()==gems[i][j].getColor() && (a<10 && b<10)){ // Check till the color does not match
count++;
a++;
b++;
}
if(count>=3){ //If 3 or more have matched
for(int a=i, b=j, c=0;c<count;++c){
gems[a][b].setColor(0);
}
return true;
}
}
}
}
}
return false;
}
if you can help me with this code please
Here's how I'd go about it. You need to do two scans. First, you need to scan for runs in one direction, then the other. It's much simpler than trying to loop through once.
I first check for horizontal runs, exiting as soon as one longer than 2 is found. Same with the vertical ones. Your function has a bool signature, so I've assumed you'll use another function to determine the location of the run - you could easily return a struct that held the position, direction and length from the findMatch method.
"use strict";
window.addEventListener('load', onLoaded, false);
var gems;
function onLoaded(evt) {
// create and initialize the array
gems = new Array();
for (var row = 0; row < 10; row++) {
let curRow = new Array();
for (var col = 0; col < 10; col++) {
let curCell = new Gem();
curCell.setColor(GetRandInRange(0, 6));
curRow.push(curCell);
}
gems.push(curRow);
}
// display it for the user
displayGems();
// check if there's 3 or more in a vertical or horizontal line.
console.log(hasMatch());
}
class Gem {
setColor(colIndex) {
this.color = colIndex;
}
getColor() {
return this.color;
}
};
function displayGems() {
var str = '';
for (var row = 0; row < 10; row++) {
if (row != 0)
str += "\n";
var dat = gems[row];
dat.forEach((gem, idx) => {
if (idx != 0)
str += ', ';
str += gem.getColor();
});
}
console.log(str);
}
function GetRandInRange(lower, upper) {
return ((Math.random() * (upper - lower)) + lower + 0.5) >> 0;
}
function hasMatch() {
let matchFound = 0;
// scan #1 - horizontally on each row
for (var row = 0; row < 10; row++) {
let last = undefined;
let runLength = 0;
for (var col = 0; col < 10; col++) {
let cur = gems[row][col].getColor();
if (cur == last) {
runLength++
if (runLength > 2) {
console.log(`horiz - ${row+1}`);
return true;
}
} else {
runLength = 0;
last = cur;
}
}
}
for (var col = 0; col < 10; col++) {
let last = undefined;
let runLength = 1;
for (var row = 0; row < 10; row++) {
let cur = gems[row][col].getColor();
if (cur == last) {
runLength++;
if (runLength > 2) {
console.log(`vert - ${col+1}`);
return true;
}
} else {
runLength = 1;
last = cur;
}
}
}
return false;
}

Value assigned by List, Changes at every iteration

This is a function of grouping events by their day. It starts with a List<EventK> which contains all the elements to sort. The result is a Map<DateTime, List<EventK>>.
The problem is with currentDayEvents. Once it is assigned to _events, and the value of currentDayEvents changes in different iterations, the value of _events also changes. How can I get the permanent value of _events outside the function?
void _getEvents()async{
setState(() {
isLoading = true;
});
List<EventK> events = await EventApi.getPersonalEvents();
List<EventK> currentDayEvents = [];
DateTime currentDay;
for(int i = 0; i<events.length-1; i++){
currentDay = events[i].startTime;
currentDayEvents.add(events[i]);
for(int j=i+1; j<events.length; j++){
DateTime analyzedDay = events[j].startTime;
if(currentDay.year == analyzedDay.year &&
currentDay.month == analyzedDay.month &&
currentDay.day == analyzedDay.day
){
currentDayEvents.add(events[j]);
events.removeAt(j);
j -= 1;
}
}
_events.putIfAbsent(currentDay, ()=>currentDayEvents);
currentDayEvents.clear();
}
setState(() {
isLoading = false;
});
}
Move the declaration of currentDayEvents inside the for-loop to reinitialise a new object on each iteration. In doing so, you can remove currentDayEvents.clear().
for(int i = 0; i<events.length-1; i++){
currentDay = events[i].startTime;
var currentDayEvents = [events[i]];
for(int j=i+1; j<events.length; j++){
DateTime analyzedDay = events[j].startTime;
if(currentDay.year == analyzedDay.year &&
currentDay.month == analyzedDay.month &&
currentDay.day == analyzedDay.day
){
currentDayEvents.add(events[j]);
events.removeAt(j);
j -= 1;
}
}
_events.putIfAbsent(currentDay, ()=>currentDayEvents);
}

How can I generate non-repeated possible combinations of a set of characters in an array?

How to generate ordered combinations for an array of characters?
For example, given an array ['a','b','c','d'], write a program for all possible combinations ordered ascendingly by length, then ascendingly by lexicographic order - in other words:
ab ac ad bc bd cd abc abd acd bcd abcd
Try this one. Although I have written it in Console application, by changing static void Main(string[] args) into a method it works.
static void Main(string[] args)
{
Dictionary<string, int> s = new Dictionary<string, int>();
Dictionary<string, int> dict = new Dictionary<string, int>();
bool bln = false;
string[] str = new string[5] { "a", "b", "c", "d","e"};
int len = str.Length;
string lastWord = "";
// a,b,c,d - count=1, aa,ab,ac,ad,ba,bb,bc,bd - count=2 etc
int count = 1;
foreach(string sa in str)
{
dict.Add(sa,1);
}
for(int m=0;m<len;m++)
{
// Gets last word as eeeee in this example
lastWord += str[4];
}
for (int i = 0; i < len; i++)
{
foreach (KeyValuePair<string, int> kvp in dict)
{
for (int j = 0; j < str.Length; j++)
{
if (kvp.Value == count)
{
s.Add(kvp.Key + str[j],count + 1);
// If last combination has reached
if (s.Keys.Contains(lastWord))
bln = true;
}
}
}
foreach (KeyValuePair<string, int> kvp in s)
{
if (kvp.Value == count + 1)
{
dict.Add(kvp.Key,kvp.Value);
}
}
if (bln)
break;
count++;
// a,b,c,d - 4 combinations. aa,ab,ac,ad,ba,bb,bc,bd...4*4=16, then 64 etc
len = len * str.Length;
}
dict.Clear();
foreach (KeyValuePair<string, int> kvp in s)
{
string s1 = SortWord(kvp.Key);
if(!dict.Keys.Contains(s1))
dict.Add(s1, kvp.Value);
}
foreach (KeyValuePair<string, int> kvp in s)
{
// abdc will get sorted to abcd
string s1 = SortWord(kvp.Key);
// If aabc then false becz 'a' is repeated two times
bool b = IsWordsRepeat(s1);
if (dict.Keys.Contains(s1) && !b)
{
dict.Remove(SortWord(kvp.Key));
}
}
Console.ReadLine();
}
Gets a boolean status to check whether a character is repeated more than 1 time
public static bool IsWordsRepeat(string text)
{
int count = 0;
foreach(char c in text)
{
count = 0;
foreach (char c1 in text)
{
if (c == c1)
{
count++;
}
if (count == 2)
return false;
}
}
return true;
}
Get word after sorting(ie, abdc to abcd)
static string SortWord(string str)
{
char[] chars = str.ToArray();
Array.Sort(chars);
return new string(chars);
}
You will get your results in dict at last in the sorted manner.
RESULT
According to your question you had asked to order the string like
ab ac ad bc bd cd abc abd acd bcd abcd
which is not in alphabetical/lexicographic order and which forms the result as follows
And as of now you are required to order in another order. Just add the below code before Console.ReadLine() which generates your desired result
var list = dict.Keys.ToList();
list.Sort();
foreach (var key in list)
{
Console.WriteLine("{0}", key);
}
which shows the below result
import java.util.*;
import java.math.*;
public class combPowerSet {
//printing the charachters as per the number sent.
void printNumber(int number, char [] items)
{
String digitString = Integer.toString(number);
char [] digitStringArray = digitString.toCharArray();
int length = digitStringArray.length;
for ( int i=0; i<length; i++)
{
System.out.print(items[Character.getNumericValue(digitStringArray[i])-1]);
}
System.out.println();
}
//checking if the number follows the required pattern.
boolean checkCondition(int number, int itemSize)
{
boolean validNumber = true;
String digitString = Integer.toString(number);
char [] digitStringArray = digitString.toCharArray();
int length = digitStringArray.length;
for ( int i=0; i<length; i++)
{
for( int j = i+1; j < length; j++)
{
int x = Character.getNumericValue(digitStringArray[i]);
int y = Character.getNumericValue(digitStringArray[j]);
if (x > itemSize-1 || y > itemSize || x > y || x==y)
{
validNumber = false;
break;
}
}
if (validNumber == false) break;
}
return validNumber;
}
void printCombinations(char [] items)
{
double maxDigit = 0;
int itemSize = items.length;
for(int i=1; i<=itemSize; i++)
{
maxDigit = maxDigit + i*Math.pow(10,itemSize-i);
}
for(int x=12; x<=maxDigit; x++)
{
if(checkCondition(x, itemSize))
{
printNumber(x, items);
}
}
}
public static void main(String [] args)
{
char [] arr = { 'a','b', 'c','d', 'e'};
combPowerSet obj = new combPowerSet();
obj.printCombinations(arr);
}
}

Choose X or O for move tic tac toe

I am making a Tic Tac Toe game and i created a function that inserts X or O into my array. I have run into one problem with my design. I call the function to make a move for X, but when it is the next players turn how do i make it call for O?
Is there a way after i put makeMove() i can just call somehow it to take in O turn instead of X. Because as you can see if i do X it will just always ask for X and not O. How can i make it choose to pull in X or O turn.
The problem is i need to only have one function that makes moves.
int main()
{
while(SOME CONDITION HERE)
{
printBoard();
cout << "Player X please choose a position: ";
makeMove('X');
cout << "Player O please choose a position: ";
makeMove('O');
}
}
int makeMove(char marker)
{
int choosePosition = 0;
cin >> choosePosition;
ticTacBoard[choosePosition - 1] = marker;
}
Start with this:
int main()
{
while(SOME CONDITION HERE)
{
printBoard();
cout << "Player X please choose a position: ";
makeMove('X');
cout << "Player O please choose a position: ";
makeMove('O');
}
}
int makeMove(char marker)
{
int choosePosition = 0;
cin >> choosePosition;
ticTacBoard[choosePosition - 1] = marker;
}
Note that you're going to want to change the SOME CONDITION HERE part, but you could quickly replace it by 1 and get the same behavior of your current script (actually, a bit better).
But you'll eventually want to put something there that makes sense -- something that will tell the program to stop prompting the players for positions and, say, declare a winner.
The following is just a more streamlined way of doing the same thing:
int main()
{
while(SOME CONDITION HERE)
{
printBoard();
makeMove('X');
makeMove('O');
}
}
int makeMove(char marker)
{
cout << "Player " << marker << " please choose a position: ";
int choosePosition = 0;
cin >> choosePosition;
ticTacBoard[choosePosition - 1] = marker;
return 0;
}
Note the added return 0 -- if you don't want to return something, you should just make makeMove return void so as not to be confusing.
You might try using an argument:
int makeMove(char player);
makeMove('O');
makeMove('X');
First of all, don't call main() recursively. Use a loop instead.
Secondly, use a variable (such as player below) to indicate whose turn it is.
int main()
{
char player = 'X';
while (/* game not finished */) {
printBoard();
makeMove(player);
player = (player == 'X') ? 'O' : 'X';
}
}
void makeMove(char player)
{
cout << "Player " << player << " please choose a position: ";
int choosePosition = 0;
cin >> choosePosition;
ticTacBoard[choosePosition - 1] = player;
}
Something like this may work... just be sure to use a loop for the moves.
char player = 'X';
while(...) {
cout << "choose position...";
makeMove(player);
if(player == 'X')
player = 'O';
else
player = 'X';
...
}
//in make move:
int makeMove(char player) {
int choosePosition = 0;
cin >> choosePosition;
ticTacBoard[choosePosition - 1] = player;
}
http://scripts.franciscocharrua.com/javascript/tic-tac-toe/
I added this to my website a few months ago. I admit it may be a bit complex, and in JavaScript, but it may be of some help.
JS:
function tic_tac_toe(blank_token, player_tokens, artificial_intelligence)
{
this.board = [[blank_token, blank_token, blank_token],
[blank_token, blank_token, blank_token],
[blank_token, blank_token, blank_token]];
this.blank_token = blank_token;
this.player_tokens = player_tokens;
this.display_choice = function() {};
this.declare_human_win = function() {};
this.declare_computer_win = function() {};
this.declare_tie = function() {};
this.artificial_intelligence = artificial_intelligence;
this.start =
function()
{
//Randomly choose a token for the human player.
var human_token_index = Math.floor(Math.random() * this.player_tokens.length);
this.human_player = this.player_tokens[human_token_index];
//Place the chosen token at the end of the array.
this.player_tokens[human_token_index] = this.player_tokens[this.player_tokens.length - 1];
this.player_tokens[this.player_tokens.length - 1] = this.human_player;
//Randomly choose a different token for the computer player.
var computer_token_index = Math.floor(Math.random() * (this.player_tokens.length - 1));
this.computer_player = this.player_tokens[computer_token_index];
//Clear the board.
for(var row = 0; row < 3; row++)
for(var collumn = 0; collumn < 3; collumn++)
{
this.place(this.blank_token, row, collumn);
}
if(Math.random() < 0.5)
{
this.turn = this.computer_player;
this.computer_turn();
}
else
{
this.turn = this.human_player;
}
};
//Returns the token of the winning player.
//If no one has won yet or the game is tied, returns the blank token.
//Used in combination with blank_token_count() to determine if the game is tied.
this.winner =
function()
{
var winner = this.blank_token;
//Check for 3 consecutive horisontal tokens.
for(var row = 0; row < 3; row++)
{
winner = this.board[row][0];
for(var collumn = 1; collumn < 3; collumn++)
{
if(this.board[row][collumn] != winner)
{
winner = this.blank_token;
}
}
if(winner != this.blank_token)
{
return(winner);
}
}
//Check for 3 consecutive vertical tokens.
for(var collumn = 0; collumn < 3; collumn++)
{
winner = this.board[0][collumn];
for(var row = 1; row < 3; row++)
{
if(this.board[row][collumn] != winner)
{
winner = this.blank_token;
}
}
if(winner != this.blank_token)
{
return(winner);
}
}
//Check for 3 consecutive diagonal tokens.
winner = this.board[0][0];
for(var row = 1; row < 3; row++)
{
if(this.board[row][row] != winner)
{
winner = this.blank_token;
}
}
if(winner != this.blank_token)
{
return(winner);
}
winner = this.board[0][2];
for(var row = 1; row < 3; row++)
{
if(this.board[row][2 - row] != winner)
{
winner = this.blank_token;
}
}
if(winner != this.blank_token)
{
return(winner);
}
return(winner);
};
this.blank_token_count =
function()
{
var blank_token_count = 0;
for(var row = 0; row < 3; row++)
for(var collumn = 0; collumn < 3; collumn++)
{
if(this.board[row][collumn] == this.blank_token)
{
blank_token_count++;
}
}
return(blank_token_count);
};
this.computer_turn =
function()
{
//Lets the computer take its turn if the game is not over.
if(this.turn != this.blank_token)
{
this.turn = this.computer_player;
var computer_move = this.artificial_intelligence();
this.place(this.computer_player, computer_move.row, computer_move.collumn);
}
};
this.human_turn =
function(row, collumn)
{
this.place(this.human_player, row, collumn);
this.computer_turn();
}
this.place =
function(token, row, collumn)
{
if(row < 3 && collumn < 3 &&
((this.turn == token && this.board[row][collumn] == this.blank_token) || token == this.blank_token))
{
this.board[row][collumn] = token;
this.display_choice(token, row, collumn)
//Finishes the game in case a of a win or a tie.
//When the board is not being reset.
if(token != this.blank_token)
{
var winner_token = this.winner();
if(winner_token == this.human_player)
{
this.declare_human_win();
this.turn = this.blank_token;
}
if(winner_token == this.computer_player)
{
this.declare_computer_win();
this.turn = this.blank_token;
}
if(winner_token == this.blank_token && this.blank_token_count() == 0)
{
this.declare_tie();
this.turn = this.blank_token;
}
//Gives the human player a turn, if the game is not over.
if(this.turn == this.computer_player)
{
this.turn = this.human_player
}
}
}
};
}