Search Results

Search found 822 results on 33 pages for 'latitude longitude'.

Page 8/33 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • How to get latitude and longitude position that stored in MySQL and use it in Android map application

    - by gunawan haruna
    I have tried to get the latitude and longitude position that was stored in MySQL. I want use the values to my Android map application. Here is my code: deskripsi.Java Button direction = (Button) findViewById (R.id.btnDir); direction.setOnClickListener(new OnClickListener(){ public void onClick(View arg0) { Intent z = getIntent(); des_lat = z.getExtras().getString("des_lat"); des_long = z.getExtras().getString("des_long"); Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?&daddr="+des_lat+","+des_long)); //("geo:37.827500,-122.481670")); startActivity(i); } }); And here is the content.Java private ListView list; int x; private String panjang[]; public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.kontent); super.initButtonSearch(); list = (ListView) findViewById(R.id.list); JSONObject jo; try { jo = new JSONObject(JsonKontent); JSONArray ja = jo.getJSONArray("result"); System.out.println("Panjang : " + ja.length()); if (ja.length() == 0) { Toast.makeText(Content.this, "Data tidak ada!", Toast.LENGTH_LONG).show(); finish(); } content_id = new String[ja.length()]; c_title = new String[ja.length()]; c_telephone = new String[ja.length()]; c_short_description = new String[ja.length()]; c_long_description = new String[ja.length()]; c_image1 = new String[ja.length()]; c_image2 = new String[ja.length()]; l_address = new String[ja.length()]; catagory_id = new String[ja.length()]; Location myLoc = new Location("sharedPreferences"); Location restLoc = new Location("restaurantTable"); l_latitude = new String[ja.length()]; l_longitude = new String[ja.length()]; c_name = new String[ja.length()]; panjang = new String[ja.length()]; for (x = 0; x < ja.length(); x++) { JSONObject joj = ja.getJSONObject(x); content_id[x] = joj.getString("content_id"); catagory_id[x] = joj.getString("catagory_id"); c_title[x] = joj.getString("c_title"); c_telephone[x] = joj.getString("c_telephone"); c_short_description[x] = joj.getString("c_short_description"); c_long_description[x] = joj.getString("c_long_description"); c_image1[x] = HTTPConnection.urlPicture + joj.getString("c_image1"); c_image2[x] = HTTPConnection.urlPicture + joj.getString("c_image2"); l_address[x] = joj.getString("l_address"); l_latitude[x] = joj.getString("l_latitude"); l_longitude[x] = joj.getString("l_longitude"); c_name[x] = joj.getString("c_name"); myLoc.setLatitude(myLatitude); myLoc.setLongitude(myLongitude); restLoc.setLatitude(Double.parseDouble(l_latitude[x])); restLoc.setLongitude(Double.parseDouble(l_longitude[x])); float f = myLoc.distanceTo(restLoc); int f_int = Math.round(f / 100); f = Float.valueOf(f_int) / 10; String dist = new DecimalFormat("#,##0.0").format(f); System.out.println("Panjang " + dist + " km"); panjang[x] = dist + " km"; } } catch (JSONException e) { Toast.makeText(Content.this, "Data yang dicari tidak ada!", Toast.LENGTH_LONG).show(); finish(); } PFCAdapter adapter = new PFCAdapter(this, c_image1, c_title, l_address, panjang); list.setAdapter(adapter); list.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub System.out.println("Content ID: " + Content.content_id[Deskripsi.id]); Deskripsi.id = arg2; waitDialog = ProgressDialog.show(Content.this, "Memuat", "Harap tunggu, sedang terhubung dengan server"); waitDialog.setIcon(R.drawable.iconnya); waitDialog.show(); new LihatRatingTask().execute(); } }); } class LihatRatingTask extends AsyncTask<Void, Void, Void> { protected Void doInBackground(Void... Arg0) { Deskripsi.jsonRating = HTTPConnection.openUrl(HTTPConnection.host + "lihat_rating.php?content_id=" + Content.content_id[Deskripsi.id]); Deskripsi.jsonSubCategory = HTTPConnection .openUrl(HTTPConnection.host + "sub_catagory_parameter.php?content_id=" + Content.content_id[Deskripsi.id]); RoutePath.place = HTTPConnection .LoadImageFromWeb(HTTPConnection.host + "Logo/" + image[Integer.valueOf(catagory_id[Deskripsi.id]) - 1]); Intent i = new Intent(Content.this, Deskripsi.class); i.putExtra("des_lat", l_latitude); i.putExtra("des_long", l_longitude); startActivity(i); waitDialog.dismiss(); return null; } protected void onPostExecute(Void result) { // TODO Auto-generated method stub super.onPostExecute(result); waitDialog.dismiss(); } } } The result is in destination EditText in maps application for Android "null,null" How to make it "destination_latitude, destination_longitude"? Help me please.

    Read the article

  • Synfony2 validation changes invalid integer to 0

    - by Craig
    I've added validation to a form and found that in some cases it is losing the invalid data I am feeding it and saving 0s instead. The output at the bottom shows that if I post the latitude as 'zzzzzz' (clearly not a number nor between -90 and 90) the form is declared as valid and saved with the value 0 How can that happen given that I have declared the input must be a number? ProxyType.php buildForm() $builder ->add('siteName', null, array('label' => 'Site name')) .... ->add('latitude', 'number', array('label' => 'Latitude')) ->add('longitude', 'number', array('label' => 'Longitude')) .... ; ProxyController.php createAction .... $postData = $request->request->get('niwa_pictbundle_proxytype'); $this->get('logger')->info('Posted latitude = '.$postData['latitude']); $form = $this->createForm(new ProxyType(), $entity); $form->bindRequest($request); if ($form->isValid()) { $this->get('logger')->info('Form declared valid : latlong ('.$entity->getLatitude().','.$entity->getLongitude().')'); .... validation.yml Acme\PictBundle\Entity\Proxy: properties: longitude: - Min: { limit: -180 } - Max: { limit: 180 } latitude: - Max: { limit: 90 } - Min: { limit: -90 } Output [2012-09-28 02:05:30] app.INFO: Posted latitude = zzzzzz [] [] [2012-09-28 02:05:30] app.INFO: Form declared valid : latlong (0,0) [] []

    Read the article

  • How to edit item in a listbox shown from reading a .csv file?

    - by Shuvo
    I am working in a project where my application can open a .csv file and read data from it. The .csv file contains the latitude, longitude of places. The application reads data from the file shows it in a static map and display icon on the right places. The application can open multiple file at a time and it opens with a new tab every time. But I am having trouble in couple of cases When I am trying to add a new point to the .csv file opened. I am able to write new point on the same file instead adding a new point data to the existing its replacing others and writing the new point only. I cannot use selectedIndexChange event to perform edit option on the listbox and then save the file. Any direction would be great. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace CourseworkExample { public partial class Form1 : Form { public GPSDataPoint gpsdp; List<GPSDataPoint> data; List<PictureBox> pictures; List<TabPage> tabs; public static int pn = 0; private TabPage currentComponent; private Bitmap bmp1; string[] symbols = { "hospital", "university" }; Image[] symbolImages; ListBox lb = new ListBox(); string name = ""; string path = ""; public Form1() { InitializeComponent(); data = new List<GPSDataPoint>(); pictures = new List<PictureBox>(); tabs = new List<TabPage>(); symbolImages = new Image[symbols.Length]; for (int i = 0; i < 2; i++) { string location = "data/" + symbols[i] + ".png"; symbolImages[i] = Image.FromFile(location); } } private void openToolStripMenuItem_Click(object sender, EventArgs e) { FileDialog ofd = new OpenFileDialog(); string filter = "CSV File (*.csv)|*.csv"; ofd.Filter = filter; DialogResult dr = ofd.ShowDialog(); if (dr.Equals(DialogResult.OK)) { int i = ofd.FileName.LastIndexOf("\\"); name = ofd.FileName; path = ofd.FileName; if (i > 0) { name = ofd.FileName.Substring(i + 1); path = ofd.FileName.Substring(0, i + 1); } TextReader input = new StreamReader(ofd.FileName); string mapName = input.ReadLine(); GPSDataPoint gpsD = new GPSDataPoint(); gpsD.setBounds(input.ReadLine()); string s; while ((s = input.ReadLine()) != null) { gpsD.addWaypoint(s); } input.Close(); TabPage tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; lb.Width = 300; int selectedindex = lb.SelectedIndex; lb.Items.Add(mapName); lb.Items.Add("Bounds"); lb.Items.Add(gpsD.Bounds[0] + " " + gpsD.Bounds[1] + " " + gpsD.Bounds[2] + " " + gpsD.Bounds[3]); lb.Items.Add("Waypoint"); foreach (WayPoint wp in gpsD.DataList) { lb.Items.Add(wp.Name + " " + wp.Latitude + " " + wp.Longitude + " " + wp.Ele + " " + wp.Sym); } tabPage.Controls.Add(lb); pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = name; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); tabControl1.Controls.Add(tabPage); tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = mapName; string location = path + mapName; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); PictureBox pb = new PictureBox(); pb.Name = "pictureBox" + pn; pb.Image = Image.FromFile(location); tabControl2.Controls.Add(tabPage); pb.Width = pb.Image.Width; pb.Height = pb.Image.Height; tabPage.Controls.Add(pb); currentComponent = tabPage; tabPage.Width = pb.Width; tabPage.Height = pb.Height; pn++; tabControl2.Width = pb.Width; tabControl2.Height = pb.Height; bmp1 = (Bitmap)pb.Image; int lx, ly; float realWidth = gpsD.Bounds[1] - gpsD.Bounds[3]; float imageW = pb.Image.Width; float dx = imageW * (gpsD.Bounds[1] - gpsD.getWayPoint(0).Longitude) / realWidth; float realHeight = gpsD.Bounds[0] - gpsD.Bounds[2]; float imageH = pb.Image.Height; float dy = imageH * (gpsD.Bounds[0] - gpsD.getWayPoint(0).Latitude) / realHeight; lx = (int)dx; ly = (int)dy; using (Graphics g = Graphics.FromImage(bmp1)) { Rectangle rect = new Rectangle(lx, ly, 20, 20); if (gpsD.getWayPoint(0).Sym.Equals("")) { g.DrawRectangle(new Pen(Color.Red), rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("hospital")) { g.DrawImage(symbolImages[0], rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("university")) { g.DrawImage(symbolImages[1], rect); } } } } pb.Image = bmp1; pb.Invalidate(); } } private void openToolStripMenuItem_Click_1(object sender, EventArgs e) { FileDialog ofd = new OpenFileDialog(); string filter = "CSV File (*.csv)|*.csv"; ofd.Filter = filter; DialogResult dr = ofd.ShowDialog(); if (dr.Equals(DialogResult.OK)) { int i = ofd.FileName.LastIndexOf("\\"); name = ofd.FileName; path = ofd.FileName; if (i > 0) { name = ofd.FileName.Substring(i + 1); path = ofd.FileName.Substring(0, i + 1); } TextReader input = new StreamReader(ofd.FileName); string mapName = input.ReadLine(); GPSDataPoint gpsD = new GPSDataPoint(); gpsD.setBounds(input.ReadLine()); string s; while ((s = input.ReadLine()) != null) { gpsD.addWaypoint(s); } input.Close(); TabPage tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; ListBox lb = new ListBox(); lb.Width = 300; lb.Items.Add(mapName); lb.Items.Add("Bounds"); lb.Items.Add(gpsD.Bounds[0] + " " + gpsD.Bounds[1] + " " + gpsD.Bounds[2] + " " + gpsD.Bounds[3]); lb.Items.Add("Waypoint"); foreach (WayPoint wp in gpsD.DataList) { lb.Items.Add(wp.Name + " " + wp.Latitude + " " + wp.Longitude + " " + wp.Ele + " " + wp.Sym); } tabPage.Controls.Add(lb); pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = name; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); tabControl1.Controls.Add(tabPage); tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = mapName; string location = path + mapName; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); PictureBox pb = new PictureBox(); pb.Name = "pictureBox" + pn; pb.Image = Image.FromFile(location); tabControl2.Controls.Add(tabPage); pb.Width = pb.Image.Width; pb.Height = pb.Image.Height; tabPage.Controls.Add(pb); currentComponent = tabPage; tabPage.Width = pb.Width; tabPage.Height = pb.Height; pn++; tabControl2.Width = pb.Width; tabControl2.Height = pb.Height; bmp1 = (Bitmap)pb.Image; int lx, ly; float realWidth = gpsD.Bounds[1] - gpsD.Bounds[3]; float imageW = pb.Image.Width; float dx = imageW * (gpsD.Bounds[1] - gpsD.getWayPoint(0).Longitude) / realWidth; float realHeight = gpsD.Bounds[0] - gpsD.Bounds[2]; float imageH = pb.Image.Height; float dy = imageH * (gpsD.Bounds[0] - gpsD.getWayPoint(0).Latitude) / realHeight; lx = (int)dx; ly = (int)dy; using (Graphics g = Graphics.FromImage(bmp1)) { Rectangle rect = new Rectangle(lx, ly, 20, 20); if (gpsD.getWayPoint(0).Sym.Equals("")) { g.DrawRectangle(new Pen(Color.Red), rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("hospital")) { g.DrawImage(symbolImages[0], rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("university")) { g.DrawImage(symbolImages[1], rect); } } } } pb.Image = bmp1; pb.Invalidate(); MessageBox.Show(data.ToString()); } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void addBtn_Click(object sender, EventArgs e) { string wayName = nameTxtBox.Text; float wayLat = Convert.ToSingle(latTxtBox.Text); float wayLong = Convert.ToSingle(longTxtBox.Text); float wayEle = Convert.ToSingle(elevTxtBox.Text); WayPoint wp = new WayPoint(wayName, wayLat, wayLong, wayEle); GPSDataPoint gdp = new GPSDataPoint(); data = new List<GPSDataPoint>(); gdp.Add(wp); lb.Items.Add(wp.Name + " " + wp.Latitude + " " + wp.Longitude + " " + wp.Ele + " " + wp.Sym); lb.Refresh(); StreamWriter sr = new StreamWriter(name); sr.Write(lb); sr.Close(); DialogResult result = MessageBox.Show("Save in New File?","Save", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.FileName = "default.csv"; DialogResult saveResult = saveDialog.ShowDialog(); if (saveResult == DialogResult.OK) { sr = new StreamWriter(saveDialog.FileName, true); sr.WriteLine(wayName + "," + wayLat + "," + wayLong + "," + wayEle); sr.Close(); } } else { // sr = new StreamWriter(name, true); // sr.WriteLine(wayName + "," + wayLat + "," + wayLong + "," + wayEle); sr.Close(); } MessageBox.Show(name + path); } } } GPSDataPoint.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace CourseworkExample { public class GPSDataPoint { private float[] bounds; private List<WayPoint> dataList; public GPSDataPoint() { dataList = new List<WayPoint>(); } internal void setBounds(string p) { string[] b = p.Split(','); bounds = new float[b.Length]; for (int i = 0; i < b.Length; i++) { bounds[i] = Convert.ToSingle(b[i]); } } public float[] Bounds { get { return bounds; } } internal void addWaypoint(string s) { WayPoint wp = new WayPoint(s); dataList.Add(wp); } public WayPoint getWayPoint(int i) { if (i < dataList.Count) { return dataList[i]; } else return null; } public List<WayPoint> DataList { get { return dataList; } } internal void Add(WayPoint wp) { dataList.Add(wp); } } } WayPoint.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CourseworkExample { public class WayPoint { private string name; private float ele; private float latitude; private float longitude; private string sym; public WayPoint(string name, float latitude, float longitude, float elevation) { this.name = name; this.latitude = latitude; this.longitude = longitude; this.ele = elevation; } public WayPoint() { name = "no name"; ele = 3.5F; latitude = 3.5F; longitude = 0.0F; sym = "no symbol"; } public WayPoint(string s) { string[] bits = s.Split(','); name = bits[0]; longitude = Convert.ToSingle(bits[2]); latitude = Convert.ToSingle(bits[1]); if (bits.Length > 4) sym = bits[4]; else sym = ""; try { ele = Convert.ToSingle(bits[3]); } catch (Exception e) { ele = 0.0f; } } public float Longitude { get { return longitude; } set { longitude = value; } } public float Latitude { get { return latitude; } set { latitude = value; } } public float Ele { get { return ele; } set { ele = value; } } public string Name { get { return name; } set { name = value; } } public string Sym { get { return sym; } set { sym = value; } } } } .csv file data birthplace.png 51.483788,-0.351906,51.460745,-0.302982 Born Here,51.473805,-0.32532,-,hospital Danced here,51,483805,-0.32532,-,hospital

    Read the article

  • Geolocation SQL query not finding exact location

    - by Iridium52
    I have been testing my geolocation query for some time now and I haven't found any issues with it until now. I am trying to search for all cities within a given radius, often times I'm searching for cities surrounding a city using that city's coords, but recently I tried searching around a city and found that the city itself was not returned. I have these cities as an excerpt in my database: city latitude longitude Saint-Mathieu 45.316708 -73.516253 Saint-Édouard 45.233374 -73.516254 Saint-Michel 45.233374 -73.566256 Saint-Rémi 45.266708 -73.616257 But when I run my query around the city of Saint-Rémi, with the following query... SELECT tblcity.city, tblcity.latitude, tblcity.longitude, truncate((degrees(acos( sin(radians(tblcity.latitude)) * sin(radians(45.266708)) + cos(radians(tblcity.latitude)) * cos(radians(45.266708)) * cos(radians(tblcity.longitude - -73.616257) ) ) ) * 69.09*1.6),1) as distance FROM tblcity HAVING distance < 10 ORDER BY distance desc I get these results: city latitude longitude distance Saint-Mathieu 45.316708 -73.516253 9.5 Saint-Édouard 45.233374 -73.516254 8.6 Saint-Michel 45.233374 -73.566256 5.3 The town of Saint-Rémi is missing from the search. So I tried a modified query hoping to get a better result: SELECT tblcity.city, tblcity.latitude, tblcity.longitude, truncate(( 6371 * acos( cos( radians( 45.266708 ) ) * cos( radians( tblcity.latitude ) ) * cos( radians( tblcity.longitude ) - radians( -73.616257 ) ) + sin( radians( 45.266708 ) ) * sin( radians( tblcity.latitude ) ) ) ),1) AS distance FROM tblcity HAVING distance < 10 ORDER BY distance desc But I get the same result... However, if I modify Saint-Rémi's coords slighly by changing the last digit of the lat or long by 1, both queries will return Saint-Rémi. Also, if I center the query on any of the other cities above, the searched city is returned in the results. Can anyone shed some light on what may be causing my queries above to not display the searched city of Saint-Rémi? I have added a sample of the table (with extra fields removed) below. I'm using MySQL 5.0.45, thanks in advance. CREATE TABLE `tblcity` ( `IDCity` int(1) NOT NULL auto_increment, `City` varchar(155) NOT NULL default '', `Latitude` decimal(9,6) NOT NULL default '0.000000', `Longitude` decimal(9,6) NOT NULL default '0.000000', PRIMARY KEY (`IDCity`) ) ENGINE=MyISAM AUTO_INCREMENT=52743 DEFAULT CHARSET=latin1 AUTO_INCREMENT=52743; INSERT INTO `tblcity` (`city`, `latitude`, `longitude`) VALUES ('Saint-Mathieu', 45.316708, -73.516253), ('Saint-Édouard', 45.233374, -73.516254), ('Saint-Michel', 45.233374, -73.566256), ('Saint-Rémi', 45.266708, -73.616257);

    Read the article

  • Converting from Latitude/Longitude to Cartesian Coordinates with a World File and map image.

    - by Heath
    I have a java applet that allows users to import a jpeg and world file from the local system. The user can then "click" draw lines on the image that was imported. Each endpoint of each line contains a set of X/Y and Lat/Long values. The XY is standard java coordinate space, the applet uses an affine transform calculation with the world file to determine the lat/long for every point on the canvas. I have a requirement that allows a user to type a distance into a text field and use the arrow key to draw a line in a certain direction (Up, Down, Left, Right) from a single selected point on the screen. I know how to determine the lat/long of a point given a source lat/long, distance, and bearing. So a user types "100" in the text field and presses the Right arrow key a line should be drawn 100 feet to the right from the currently selected point. My issue is I don't know how to convert the distance( which is in feet ) into the distance in pixels. This would then tell my where to plot the point.

    Read the article

  • How can I transform latitude and longitude to x,y in Java?

    - by hory.incpp
    Hello, I am working on a geographic project in Java. The input are coordinates : 24.4444 N etc Output: a PLAIN map (not round) showing the point of the coordinates. I don't know the algorithm to transform from coordinates to x,y on a JComponent, can somebody help me? The map looks like this: http://upload.wikimedia.org/wikipedia/commons/7/74/Mercator-projection.jpg Thank you

    Read the article

  • Using lattitude and longitude of the current location and destination location , how can we get the direction in iphone

    - by ratnasomu
    Hello Everyone , I am working in 1 iphone app where we need to show the direction from 1 place to other place That is from current location in which direction (N or E or W or S or NE or NW or SE or SW ) the destination is . I know how to get the directions from 1 place to another place but I am searching for showing the direction . Is my problem clear ? If any one know how to do it , Pleae help me Thanks every one!

    Read the article

  • sqlite select query round of double value

    - by Scorpion
    I have stored location in my sqlite database. CREATE TABLE city ( latitude NUMERIC, longitude NUMERIC ) Below are the value :- latitude = 41.0776605;//actual value in db - NUMERIC stored as DB longitude = -74.170086;//actual value in db - NUMERIC stored as DB final String query = "SELECT * FROM city"; cursor = myDataBase.rawQuery(query, null); if (null != cursor) { while (cursor.moveToNext()) { Log.i(TAG, "Latitude == " + cursor.getDouble(cursor.getColumnIndex("latitude"))); Log.i(TAG, "Longitude == " + cursor.getDouble(cursor.getColumnIndex("longitude"))); } } Result :- Latitude = 40.4127 Longitude = -74.25252 I don't want round off this values. Is there any way to solve this problem.

    Read the article

  • PHP JSON encode output number as string

    - by mitch
    I am trying to output a JSON string using PHP and MySQL but the latitude and longitude is outputting as a string with quotes around the values. This causes an issue when I am trying to add the markers to a google map. Here is my code: $sql = mysql_query('SELECT * FROM markers WHERE address !=""'); $results = array(); while($row = mysql_fetch_array($sql)) { $results[] = array( 'latitude' =>$row['lat'], 'longitude' => $row['lng'], 'address' => $row['address'], 'project_ID' => $row['project_ID'], 'marker_id' => $row['marker_id'] ); } $json = json_encode($results); echo "{\"markers\":"; echo $json; echo "}"; Here is the expected output: {"markers":[{"latitude":0.000000,"longitude":0.000000,"address":"2234 2nd Ave, Seattle, WA","project_ID":"7","marker_id":"21"}]} Here is the output that I am getting: {"markers":[{"latitude":"0.000000","longitude":"0.000000","address":"2234 2nd Ave, Seattle, WA","project_ID":"7","marker_id":"21"}]} Notice the quotes around the latitude and longitude values.

    Read the article

  • Finding Cities within 'X' Kilometers (or Miles)

    - by Mike Curry
    This may or may not be clear, leave me a comment if I am off base, or you need more information. Perhaps there is a solution out there already for what I want in PHP. I am looking for a function that will add or subtract a distance from a longitude OR latitude value. Reason: I have a database with all Latitudes and Longitudes in it and want to form a query to extract all cities within X kilometers (or miles). My query would look something like this... Select * From Cities Where (Longitude > X1 and Longitude < X2) And (Latitude > Y1 and Latitude < Y2) Where X1 = Longitude - (distance) Where X2 = Longitude + (distance) Where Y1 = Latitude - (distance) Where Y2 = Latitude + (distance) I am working in PHP, with a MySql Database. Open to any suggestions also! :)

    Read the article

  • How to fetch managed objects sorted by calculated value

    - by Marcin Zbijowski
    Hello, I'm working on the app that uses CoreData. There is location entity that holds latitude and longitude values. I'd like to fetch those entities sorted by distance to the user's location. I tried to set sort descriptor to distance formula sqrt ((x1 - x2)^2 + (y1 - y2)^2) but it fails with exception "... keypath ... not found in entity". NSString *distanceFormula = [NSString stringWithFormat:@"sqrt(((latitude - %f) * (latitude - %f)) + ((longitude - %f) * (longitude - %f)))", location.coordinate.latitude, location.coordinate.latitude, location.coordinate.longitude, location.coordinate.longitude]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:distanceFormula ascending:YES]; [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]]; NSError *error; NSArray *result = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error]; I'd like to fetch already sorted objects rather then fetch them all and then sort in the code. Any tips appreciated.

    Read the article

  • Setting corelocation results to NSNumber object parameters

    - by Dan Ray
    This is a weird one, y'all. - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { CLLocationCoordinate2D coordinate = newLocation.coordinate; self.mark.longitude = [NSNumber numberWithDouble:coordinate.longitude]; self.mark.latitude = [NSNumber numberWithDouble:coordinate.latitude]; NSLog(@"Got %f %f, set %f %f", coordinate.latitude, coordinate.longitude, self.mark.latitude, self.mark.longitude); [manager stopUpdatingLocation]; manager.delegate = nil; if (self.waitingForLocation) { [self completeUpload]; } } The latitude and longitude in that "mark" object are synthesized parameters referring to NSNumber iVars. In the simulator, my NSLog output for that line in the middle there reads: 2010-05-28 15:08:46.938 EverWondr[8375:207] Got 37.331689 -122.030731, set 0.000000 -44213283338325225829852024986561881455984640.000000 That's a WHOLE lot further East than 1 Infinite Loop! The numbers are different on the device, but similar--lat is still zero and long is a very unlikely high negative number. Elsewhere in the controller I'm accepting a button press and uploading a file (an image I just took with the camera) with its geocoding info associated, and I need that self.waitingForLocation to inform the CLLocationManager delegate that I already hit that button and once its done its deal, it should go ahead and fire off the upload. Thing is, up in the button-click-receiving method, I test see if CL is finished by testing self.mark.latitude, which seems to be getting set zero...

    Read the article

  • How deserealizing JSON with GSON

    - by loko
    I have one result of APPI http://developer.yahoo.com/geo/placefinder/guide/examples.html, I need to deserealizing the result JSON of example only with GSON http://where.yahooapis.com/geocode?location=San+Francisco,+CA&flags=J&appid=yourappid But i dont now have to do the class for deserealizing one JSON with array This is the reponse: {"ResultSet": {"version":"1.0", "Error":0, "ErrorMessage":"No error", "Locale":"en_US", "Quality":40, "Found":1, "Results":[ {"quality":40, "latitude":"37.779160", "longitude":"-122.420049", "offsetlat":"37.779160", "offsetlon":"-122.420049", "radius":5000, "name":"", "line1":"", "line2":"San Francisco, CA", "line3":"", "line4":"United States", "house":"", "street":"", "xstreet":"", "unittype":"", "unit":"", "postal":"", "neighborhood":"", "city":"San Francisco", "county":"San Francisco County", "state":"California", "country":"United States", "countrycode":"US", "statecode":"CA", "countycode":"", "uzip":"94102", "hash":"C1D313AD706E3B3C", "woeid":12587707, "woetype":9}] } } Im trying to deserealizing of this way but i couldn´t do that, please help me to do the correct class to get the JSON with GSON. public class LocationAddress { private ResultSet resultset; public static class ResultSet{ private String version; private String Error; private String ErrorMessage; private List<Results> results; } public static class Results{ private String quality; private String latitude; private String longitude; public String getQuality() { return quality; } public void setQuality(String quality) { this.quality = quality; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } } }

    Read the article

  • Shortest Distance From An Array

    - by notyou61
    I have an ajax function which returns the latitudes and longitudes of locations stored in a database. These are returned and placed in an array. A calculation is performed to return their distance from the users current location based on the latitude/longitude. I would like to return only the record with the shortest calculated distance. My code is as follows: Ajax Success // Success success: function (data) { // Obtain Log/Lat navigator.geolocation.getCurrentPosition(function(position) { // Obtain Current Position Lat/Lon glbVar.latitude = position.coords.latitude; glbVar.longitude = position.coords.longitude; // Console Log //console.log('Lat: ' + glbVar.latitude + ' Lon: ' + glbVar.longitude); // Obtain Location Distances for ( var i = 0; i < data.length; i++ ) { // Location Instances var varLocation = data[i]; // Location Distance varLocation.distance = calculateDistance(glbVar.longitude, glbVar.latitude, varLocation.locationLongitude, varLocation.locationLatitude); } // Sort Locations By Distance var sortedData = data.sort(function(a, b) { // Return Locations return a.distance - b.distance; }); // Output Results $.map(sortedData, function(item) { // Obtain Location Distance varLocationsDistance = calculateDistance(glbVar.longitude, glbVar.latitude, item.locationLongitude, item.locationLatitude); // Obtain Location Radius Assignment if (varLocationsDistance <= varLocationRadius) { // Function Return functionReturn = $({locationID : item.locationID + ', Distance : ' + varLocationsDistance + ' m'}); // Return // Function to get the Min value in Array Array.min = function( sortedData ){ functionReturn = Math.min.apply( Math, sortedData ); // console.log(functionReturn); }; } }); }); } The calculateDistance function returns the distance from the users current location and those from the database. The varLocationsDistance <= varLocationRadius "If" statement returns records within a certain distance radius (100 meters), within that statement I would like to return the shortest distance. I am a self taught amateur web developer and as a result may not have provide enough information for an answer, please let me know. Thanks,

    Read the article

  • Basic Spatial Data with SQL Server and Entity Framework 5.0

    - by Rick Strahl
    In my most recent project we needed to do a bit of geo-spatial referencing. While spatial features have been in SQL Server for a while using those features inside of .NET applications hasn't been as straight forward as could be, because .NET natively doesn't support spatial types. There are workarounds for this with a few custom project like SharpMap or a hack using the Sql Server specific Geo types found in the Microsoft.SqlTypes assembly that ships with SQL server. While these approaches work for manipulating spatial data from .NET code, they didn't work with database access if you're using Entity Framework. Other ORM vendors have been rolling their own versions of spatial integration. In Entity Framework 5.0 running on .NET 4.5 the Microsoft ORM finally adds support for spatial types as well. In this post I'll describe basic geography features that deal with single location and distance calculations which is probably the most common usage scenario. SQL Server Transact-SQL Syntax for Spatial Data Before we look at how things work with Entity framework, lets take a look at how SQL Server allows you to use spatial data to get an understanding of the underlying semantics. The following SQL examples should work with SQL 2008 and forward. Let's start by creating a test table that includes a Geography field and also a pair of Long/Lat fields that demonstrate how you can work with the geography functions even if you don't have geography/geometry fields in the database. Here's the CREATE command:CREATE TABLE [dbo].[Geo]( [id] [int] IDENTITY(1,1) NOT NULL, [Location] [geography] NULL, [Long] [float] NOT NULL, [Lat] [float] NOT NULL ) Now using plain SQL you can insert data into the table using geography::STGeoFromText SQL CLR function:insert into Geo( Location , long, lat ) values ( geography::STGeomFromText ('POINT(-121.527200 45.712113)', 4326), -121.527200, 45.712113 ) insert into Geo( Location , long, lat ) values ( geography::STGeomFromText ('POINT(-121.517265 45.714240)', 4326), -121.517265, 45.714240 ) insert into Geo( Location , long, lat ) values ( geography::STGeomFromText ('POINT(-121.511536 45.714825)', 4326), -121.511536, 45.714825) The STGeomFromText function accepts a string that points to a geometric item (a point here but can also be a line or path or polygon and many others). You also need to provide an SRID (Spatial Reference System Identifier) which is an integer value that determines the rules for how geography/geometry values are calculated and returned. For mapping/distance functionality you typically want to use 4326 as this is the format used by most mapping software and geo-location libraries like Google and Bing. The spatial data in the Location field is stored in binary format which looks something like this: Once the location data is in the database you can query the data and do simple distance computations very easily. For example to calculate the distance of each of the values in the database to another spatial point is very easy to calculate. Distance calculations compare two points in space using a direct line calculation. For our example I'll compare a new point to all the points in the database. Using the Location field the SQL looks like this:-- create a source point DECLARE @s geography SET @s = geography:: STGeomFromText('POINT(-121.527200 45.712113)' , 4326); --- return the ids select ID, Location as Geo , Location .ToString() as Point , @s.STDistance( Location) as distance from Geo order by distance The code defines a new point which is the base point to compare each of the values to. You can also compare values from the database directly, but typically you'll want to match a location to another location and determine the difference for which you can use the geography::STDistance function. This query produces the following output: The STDistance function returns the straight line distance between the passed in point and the point in the database field. The result for SRID 4326 is always in meters. Notice that the first value passed was the same point so the difference is 0. The other two points are two points here in town in Hood River a little ways away - 808 and 1256 meters respectively. Notice also that you can order the result by the resulting distance, which effectively gives you results that are ordered radially out from closer to further away. This is great for searches of points of interest near a central location (YOU typically!). These geolocation functions are also available to you if you don't use the Geography/Geometry types, but plain float values. It's a little more work, as each point has to be created in the query using the string syntax, but the following code doesn't use a geography field but produces the same result as the previous query.--- using float fields select ID, geography::STGeomFromText ('POINT(' + STR (long, 15,7 ) + ' ' + Str(lat ,15, 7) + ')' , 4326), geography::STGeomFromText ('POINT(' + STR (long, 15,7 ) + ' ' + Str(lat ,15, 7) + ')' , 4326). ToString(), @s.STDistance( geography::STGeomFromText ('POINT(' + STR(long ,15, 7) + ' ' + Str(lat ,15, 7) + ')' , 4326)) as distance from geo order by distance Spatial Data in the Entity Framework Prior to Entity Framework 5.0 on .NET 4.5 consuming of the data above required using stored procedures or raw SQL commands to access the spatial data. In Entity Framework 5 however, Microsoft introduced the new DbGeometry and DbGeography types. These immutable location types provide a bunch of functionality for manipulating spatial points using geometry functions which in turn can be used to do common spatial queries like I described in the SQL syntax above. The DbGeography/DbGeometry types are immutable, meaning that you can't write to them once they've been created. They are a bit odd in that you need to use factory methods in order to instantiate them - they have no constructor() and you can't assign to properties like Latitude and Longitude. Creating a Model with Spatial Data Let's start by creating a simple Entity Framework model that includes a Location property of type DbGeography: public class GeoLocationContext : DbContext { public DbSet<GeoLocation> Locations { get; set; } } public class GeoLocation { public int Id { get; set; } public DbGeography Location { get; set; } public string Address { get; set; } } That's all there's to it. When you run this now against SQL Server, you get a Geography field for the Location property, which looks the same as the Location field in the SQL examples earlier. Adding Spatial Data to the Database Next let's add some data to the table that includes some latitude and longitude data. An easy way to find lat/long locations is to use Google Maps to pinpoint your location, then right click and click on What's Here. Click on the green marker to get the GPS coordinates. To add the actual geolocation data create an instance of the GeoLocation type and use the DbGeography.PointFromText() factory method to create a new point to assign to the Location property:[TestMethod] public void AddLocationsToDataBase() { var context = new GeoLocationContext(); // remove all context.Locations.ToList().ForEach( loc => context.Locations.Remove(loc)); context.SaveChanges(); var location = new GeoLocation() { // Create a point using native DbGeography Factory method Location = DbGeography.PointFromText( string.Format("POINT({0} {1})", -121.527200,45.712113) ,4326), Address = "301 15th Street, Hood River" }; context.Locations.Add(location); location = new GeoLocation() { Location = CreatePoint(45.714240, -121.517265), Address = "The Hatchery, Bingen" }; context.Locations.Add(location); location = new GeoLocation() { // Create a point using a helper function (lat/long) Location = CreatePoint(45.708457, -121.514432), Address = "Kaze Sushi, Hood River" }; context.Locations.Add(location); location = new GeoLocation() { Location = CreatePoint(45.722780, -120.209227), Address = "Arlington, OR" }; context.Locations.Add(location); context.SaveChanges(); } As promised, a DbGeography object has to be created with one of the static factory methods provided on the type as the Location.Longitude and Location.Latitude properties are read only. Here I'm using PointFromText() which uses a "Well Known Text" format to specify spatial data. In the first example I'm specifying to create a Point from a longitude and latitude value, using an SRID of 4326 (just like earlier in the SQL examples). You'll probably want to create a helper method to make the creation of Points easier to avoid that string format and instead just pass in a couple of double values. Here's my helper called CreatePoint that's used for all but the first point creation in the sample above:public static DbGeography CreatePoint(double latitude, double longitude) { var text = string.Format(CultureInfo.InvariantCulture.NumberFormat, "POINT({0} {1})", longitude, latitude); // 4326 is most common coordinate system used by GPS/Maps return DbGeography.PointFromText(text, 4326); } Using the helper the syntax becomes a bit cleaner, requiring only a latitude and longitude respectively. Note that my method intentionally swaps the parameters around because Latitude and Longitude is the common format I've seen with mapping libraries (especially Google Mapping/Geolocation APIs with their LatLng type). When the context is changed the data is written into the database using the SQL Geography type which looks the same as in the earlier SQL examples shown. Querying Once you have some location data in the database it's now super easy to query the data and find out the distance between locations. A common query is to ask for a number of locations that are near a fixed point - typically your current location and order it by distance. Using LINQ to Entities a query like this is easy to construct:[TestMethod] public void QueryLocationsTest() { var sourcePoint = CreatePoint(45.712113, -121.527200); var context = new GeoLocationContext(); // find any locations within 5 kilometers ordered by distance var matches = context.Locations .Where(loc => loc.Location.Distance(sourcePoint) < 5000) .OrderBy( loc=> loc.Location.Distance(sourcePoint) ) .Select( loc=> new { Address = loc.Address, Distance = loc.Location.Distance(sourcePoint) }); Assert.IsTrue(matches.Count() > 0); foreach (var location in matches) { Console.WriteLine("{0} ({1:n0} meters)", location.Address, location.Distance); } } This example produces: 301 15th Street, Hood River (0 meters)The Hatchery, Bingen (809 meters)Kaze Sushi, Hood River (1,074 meters)   The first point in the database is the same as my source point I'm comparing against so the distance is 0. The other two are within the 5 mile radius, while the Arlington location which is 65 miles or so out is not returned. The result is ordered by distance from closest to furthest away. In the code, I first create a source point that is the basis for comparison. The LINQ query then selects all locations that are within 5km of the source point using the Location.Distance() function, which takes a source point as a parameter. You can either use a pre-defined value as I'm doing here, or compare against another database DbGeography property (say when you have to points in the same database for things like routes). What's nice about this query syntax is that it's very clean and easy to read and understand. You can calculate the distance and also easily order by the distance to provide a result that shows locations from closest to furthest away which is a common scenario for any application that places a user in the context of several locations. It's now super easy to accomplish this. Meters vs. Miles As with the SQL Server functions, the Distance() method returns data in meters, so if you need to work with miles or feet you need to do some conversion. Here are a couple of helpers that might be useful (can be found in GeoUtils.cs of the sample project):/// <summary> /// Convert meters to miles /// </summary> /// <param name="meters"></param> /// <returns></returns> public static double MetersToMiles(double? meters) { if (meters == null) return 0F; return meters.Value * 0.000621371192; } /// <summary> /// Convert miles to meters /// </summary> /// <param name="miles"></param> /// <returns></returns> public static double MilesToMeters(double? miles) { if (miles == null) return 0; return miles.Value * 1609.344; } Using these two helpers you can query on miles like this:[TestMethod] public void QueryLocationsMilesTest() { var sourcePoint = CreatePoint(45.712113, -121.527200); var context = new GeoLocationContext(); // find any locations within 5 miles ordered by distance var fiveMiles = GeoUtils.MilesToMeters(5); var matches = context.Locations .Where(loc => loc.Location.Distance(sourcePoint) <= fiveMiles) .OrderBy(loc => loc.Location.Distance(sourcePoint)) .Select(loc => new { Address = loc.Address, Distance = loc.Location.Distance(sourcePoint) }); Assert.IsTrue(matches.Count() > 0); foreach (var location in matches) { Console.WriteLine("{0} ({1:n1} miles)", location.Address, GeoUtils.MetersToMiles(location.Distance)); } } which produces: 301 15th Street, Hood River (0.0 miles)The Hatchery, Bingen (0.5 miles)Kaze Sushi, Hood River (0.7 miles) Nice 'n simple. .NET 4.5 Only Note that DbGeography and DbGeometry are exclusive to Entity Framework 5.0 (not 4.4 which ships in the same NuGet package or installer) and requires .NET 4.5. That's because the new DbGeometry and DbGeography (and related) types are defined in the 4.5 version of System.Data.Entity which is a CLR assembly and is only updated by major versions of .NET. Why this decision was made to add these types to System.Data.Entity rather than to the frequently updated EntityFramework assembly that would have possibly made this work in .NET 4.0 is beyond me, especially given that there are no native .NET framework spatial types to begin with. I find it also odd that there is no native CLR spatial type. The DbGeography and DbGeometry types are specific to Entity Framework and live on those assemblies. They will also work for general purpose, non-database spatial data manipulation, but then you are forced into having a dependency on System.Data.Entity, which seems a bit silly. There's also a System.Spatial assembly that's apparently part of WCF Data Services which in turn don't work with Entity framework. Another example of multiple teams at Microsoft not communicating and implementing the same functionality (differently) in several different places. Perplexed as a I may be, for EF specific code the Entity framework specific types are easy to use and work well. Working with pre-.NET 4.5 Entity Framework and Spatial Data If you can't go to .NET 4.5 just yet you can also still use spatial features in Entity Framework, but it's a lot more work as you can't use the DbContext directly to manipulate the location data. You can still run raw SQL statements to write data into the database and retrieve results using the same TSQL syntax I showed earlier using Context.Database.ExecuteSqlCommand(). Here's code that you can use to add location data into the database:[TestMethod] public void RawSqlEfAddTest() { string sqlFormat = @"insert into GeoLocations( Location, Address) values ( geography::STGeomFromText('POINT({0} {1})', 4326),@p0 )"; var sql = string.Format(sqlFormat,-121.527200, 45.712113); Console.WriteLine(sql); var context = new GeoLocationContext(); Assert.IsTrue(context.Database.ExecuteSqlCommand(sql,"301 N. 15th Street") > 0); } Here I'm using the STGeomFromText() function to add the location data. Note that I'm using string.Format here, which usually would be a bad practice but is required here. I was unable to use ExecuteSqlCommand() and its named parameter syntax as the longitude and latitude parameters are embedded into a string. Rest assured it's required as the following does not work:string sqlFormat = @"insert into GeoLocations( Location, Address) values ( geography::STGeomFromText('POINT(@p0 @p1)', 4326),@p2 )";context.Database.ExecuteSqlCommand(sql, -121.527200, 45.712113, "301 N. 15th Street") Explicitly assigning the point value with string.format works however. There are a number of ways to query location data. You can't get the location data directly, but you can retrieve the point string (which can then be parsed to get Latitude and Longitude) and you can return calculated values like distance. Here's an example of how to retrieve some geo data into a resultset using EF's and SqlQuery method:[TestMethod] public void RawSqlEfQueryTest() { var sqlFormat = @" DECLARE @s geography SET @s = geography:: STGeomFromText('POINT({0} {1})' , 4326); SELECT Address, Location.ToString() as GeoString, @s.STDistance( Location) as Distance FROM GeoLocations ORDER BY Distance"; var sql = string.Format(sqlFormat, -121.527200, 45.712113); var context = new GeoLocationContext(); var locations = context.Database.SqlQuery<ResultData>(sql); Assert.IsTrue(locations.Count() > 0); foreach (var location in locations) { Console.WriteLine(location.Address + " " + location.GeoString + " " + location.Distance); } } public class ResultData { public string GeoString { get; set; } public double Distance { get; set; } public string Address { get; set; } } Hopefully you don't have to resort to this approach as it's fairly limited. Using the new DbGeography/DbGeometry types makes this sort of thing so much easier. When I had to use code like this before I typically ended up retrieving data pks only and then running another query with just the PKs to retrieve the actual underlying DbContext entities. This was very inefficient and tedious but it did work. Summary For the current project I'm working on we actually made the switch to .NET 4.5 purely for the spatial features in EF 5.0. This app heavily relies on spatial queries and it was worth taking a chance with pre-release code to get this ease of integration as opposed to manually falling back to stored procedures or raw SQL string queries to return spatial specific queries. Using native Entity Framework code makes life a lot easier than the alternatives. It might be a late addition to Entity Framework, but it sure makes location calculations and storage easy. Where do you want to go today? ;-) Resources Download Sample Project© Rick Strahl, West Wind Technologies, 2005-2012Posted in ADO.NET  Sql Server  .NET   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Sphere Texture Mapping shows visible seams

    - by AvengerDr
    As you can see from the above picture there is a visible seam in the texture mapping. The underlying mesh is a geosphere based on octahedron subdivisions. On that particular latitude, vertices have been duplicated. However there still is a visible seam. Here is how I calculate the UV coordinates: float longitude = (float)Math.Atan2(normal.X, -normal.Z); float latitude = (float)Math.Acos(normal.Y); float u = (float)(longitude / (Math.PI * 2.0) + 0.5); float v = (float)(latitude / Math.PI); Is this a problem in the coordinates or a mipmapping issue?

    Read the article

  • iPhone Objective C - error: pointer value used where a floating point value was expected

    - by Mausimo
    I do not understand why i am getting this error. Here is the related code: Photo.h #import <CoreData/CoreData.h> @class Person; @interface Photo : NSManagedObject { } @property (nonatomic, retain) NSData * imageData; @property (nonatomic, retain) NSNumber * Latitude; @property (nonatomic, retain) NSString * ImageName; @property (nonatomic, retain) NSString * ImagePath; @property (nonatomic, retain) NSNumber * Longitude; @property (nonatomic, retain) Person * PhotoToPerson; @end Photo.m #import "Photo.h" #import "Person.h" @implementation Photo @dynamic imageData; @dynamic Latitude; @dynamic ImageName; @dynamic ImagePath; @dynamic Longitude; @dynamic PhotoToPerson; @end This is a mapViewController.m class i have created. If i run this, the CLLocationDegrees CLLat and CLLong lines: CLLocationDegrees CLLat = (CLLocationDegrees)photo.Latitude; CLLocationDegrees CLLong = (CLLocationDegrees)photo.Longitude; give me the error : pointer value used where a floating point value was expected. for(int i = 0; i < iPerson; i++) { //get the person that corresponds to the row indexPath that is currently being rendered and set the text Person * person = (Person *)[myArrayPerson objectAtIndex:i]; //get the photos associated with the person NSArray * PhotoArray = [person.PersonToPhoto allObjects]; int iPhoto = [PhotoArray count]; for(int j = 0; j < iPhoto; j++) { //get the first photo (all people will have atleast 1 photo, else they will not exist). Set the image Photo * photo = (Photo *)[PhotoArray objectAtIndex:j]; if(photo.Latitude != nil && photo.Longitude != nil) { MyAnnotation *ann = [[MyAnnotation alloc] init]; ann.title = photo.ImageName; ann.subtitle = photo.ImageName; CLLocationCoordinate2D cord; CLLocationDegrees CLLat = (CLLocationDegrees)photo.Latitude; CLLocationDegrees CLLong = (CLLocationDegrees)photo.Longitude; cord.latitude = CLLat; cord.longitude = CLLong; ann.coordinate = cord; [mkMapView addAnnotation:ann]; } } }

    Read the article

  • what to do when Bing api provides inaccurate results

    - by hao
    I am trying to use the bing Phonebook search for locations in China, but all the latitude and longitude are inaccurate. Using the following http://api.bing.net/xml.aspx?AppId=appid&Query=nike&Sources=Phonebook&Latitude=39.9883699&Longitude=116.3309665&Radius=30.0&Phonebook.Count=10&Phonebook.Offset=30 I get multiple locations with the same latitude and longitude, and the rounding is off as well. The latitude and longitude will always end with either .x00001 or .0. The results from the pho:LocalSerpUrl http://www.bing.com/shenghuo/default.aspx?what=nike&where=&s_cid=ansPhBkYp01&ac=false&FORM=SOAPGN /pho:LocalSerpUrl Is right, but the results from the returned xml is off. Also it seems users outside of China can't hit that url and get the result. So I am wondering how I can contact bing and inquire about this problem

    Read the article

  • Blackberry.location API not working correctly

    - by chibineku
    I am experimenting with making Blackberry widgets but having a little trouble. My first trial involves displaying a button which, when clicked, calls a JavaScript function that should alert the phones latitude and longitude. The function looks: function whereAmI() { var latitude = blackberry.location.latitude; var longitude = blackberry.location.longitude; alert("Lat: "+latitude+", Long: "+longitude); } But it only ever alerts "Lat: 0, Long: 0". I've checked and my GPS seems to be working ok. I'm running OS 5.* on a Curve 8900. Any help would be appreciated :)

    Read the article

  • Updating / refreshing a live geojson layer | JSON & JS Variable

    - by Ozaki
    TLDR I am trying to get my geoJSON layer to update, currently it will 1. Create the vector mark, 2. Remove the vector mark, 3. Set the JS variable for lat and lon, 4. Unset the variable??? :S Hey S O. I have a geojson layer set up as follows: //GeoJSON Layer// var layer1 = new OpenLayers.Layer.GML("My GeoJSON Layer", "coordinates", {format: OpenLayers.Format.GeoJSON, styleMap: style_red}); My features are set up as follows: var latitude = 0.0; // as 0.0 it will draw the point in. var longitude = 0.0; // as 0.0 it will draw the point in. //var longitude = getlongitude; where getlongitude = JSON string of longitude. var point = new OpenLayers.Geometry.Point(longitude, latitude); pointFeature = new OpenLayers.Feature.Vector(point, null, style_red); var style_red = OpenLayers.Util.extend({}, layer_style); style_red.strokeColor = "red"; style_red.fillColor = "black"; style_red.fillOpacity = 0.5; style_red.graphicName = "circle"; style_red.pointRadius = 3.8; style_red.strokeWidth = 2; style_red.strokeLinecap = "butt"; and my layer updating function: function UpdateLayer(){ var p = new OpenLayers.Format.GeoJSON({ 'internalProjection': new OpenLayers.Projection("EPSG:900913"), 'externalProjection': new OpenLayers.Projection("EPSG:4326") }); var url = "coordinates"; OpenLayers.loadURL(url, {}, null, function(r) { var f = p.read(r.responseText); map.layers[2].destroyFeatures(); map.layers[2].addFeatures(pointFeature); }); setTimeout("UpdateLayer()",1000) } Any idea what I am doing wrong or what I am missing? Edit1 It now removes the feature (was map.layers[1]) previously... But will not add the new feature.. Edit2 I managed to get it to redraw a point but not with live data. It should draw the point at what (latitude) & (longitude) are equal to. I am trying to set latitude & longitude to some JSON string but every time straight after it sets the variable it changes it back to "undefined" as soon as it passes the line after var latitude? (using firebug & firequery to debug)

    Read the article

  • SQL Join to only the maximum row puzzle

    - by Billy ONeal
    Given the following example data: Users +--------------------------------------------------+ | ID | First Name | Last Name | Network Identifier | +--------------------------------------------------+ | 1 | Billy | O'Neal | bro4 | +----+------------+-----------+--------------------+ | 2 | John | Skeet | jsk1 | +----+------------+-----------+--------------------+ Hardware +----+-------------------+---------------+ | ID | Hardware Name | Serial Number | +----+-------------------+---------------+ | 1 | Latitude E6500 | 5555555 | +----+-------------------+---------------+ | 2 | Latitude E6200 | 2222222 | +----+-------------------+---------------+ HardwareAssignments +---------+-------------+-------------+ | User ID | Hardware ID | Assigned On | +---------+-------------+-------------+ | 1 | 1 | April 1 | +---------+-------------+-------------+ | 1 | 2 | April 10 | +---------+-------------+-------------+ | 2 | 2 | April 1 | +---------+-------------+-------------+ | 2 | 1 | April 11 | +---------+-------------+-------------+ I'd like to write a SQL query which would give the following result: +--------------------+------------+-----------+----------------+---------------+-------------+ | Network Identifier | First Name | Last Name | Hardware Name | Serial Number | Assigned On | +--------------------+------------+-----------+----------------+---------------+-------------+ | bro4 | Billy | O'Neal | Latitude E6200 | 2222222 | April 10 | +--------------------+------------+-----------+----------------+---------------+-------------+ | jsk1 | John | Skeet | Latitude E6500 | 5555555 | April 11 | +--------------------+------------+-----------+----------------+---------------+-------------+ My trouble is that the maximum "Assigned On" date for each user needs to be selected for each individual user and used for the actual join ... Is there a clever way accomplish this in SQL?

    Read the article

  • wait for CLLocationManager to finish before tweeting

    - by user295944
    I want to wait for latitude.text and longtitude.text to be filled in before sending a tweet, this code works fine, but I would rather not put the tweeting part in locationManager because I also want to sometimes update the current location without sending a tweet. How can I make sure the txt gets filled in before sending the tweet without doing this? - (IBAction)update { latitude.text =@""; longitude.text =@""; locmanager = [[CLLocationManager alloc] init]; [locmanager setDelegate:self]; [locmanager setDesiredAccuracy:kCLLocationAccuracyBest]; [locmanager startUpdatingLocation]; } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { CLLocationCoordinate2D location = [newLocation coordinate]; latitude.text = [NSString stringWithFormat: @"%f", location.latitude]; longitude.text = [NSString stringWithFormat: @"%f", location.longitude]; TwitterRequest * t = [[TwitterRequest alloc] init]; t.username = @"****"; t.password = @"****"; [twitterMessageText resignFirstResponder]; loadingActionSheet = [[UIActionSheet alloc] initWithTitle:@"Posting To Twitter..." delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil]; [loadingActionSheet showInView:self.view]; [t statuses_update:twitterMessageText.text andLat:latitude.text andLong:longitude.text delegate:self requestSelector:@selector(status_updateCallback:)]; twitterMessageText.text=@""; }

    Read the article

  • iPhone current user location coordinates showing as (0,0)

    - by ennuikiller
    I'm trying to get the users current latitude and longitude with this viewDidLoad method. The resulting map is correctly indicating the current location however the NSLog consistently shows: 2009-09-19 16:45:29.765 Mapper[671:207] user latitude = 0.000000 2009-09-19 16:45:29.772 Mapper[671:207] user longitude = 0.000000 Anyone know what I am missing here? Thanks in advance for your help! - (void)viewDidLoad { [super viewDidLoad]; [mapView setMapType:MKMapTypeStandard]; [mapView setZoomEnabled:YES]; [mapView setScrollEnabled:YES]; [mapView setShowsUserLocation:YES]; CLLocation *userLoc = mapView.userLocation.location; CLLocationCoordinate2D userCoordinate = userLoc.coordinate; NSLog(@"user latitude = %f",userCoordinate.latitude); NSLog(@"user longitude = %f",userCoordinate.longitude); }

    Read the article

  • Rails Pretty URL with Decimals

    - by Kevin Sylvestre
    I have a rails application that allows searches using longitude and latitude. I have added a 'pretty' route with: map.connect 'stores/near/:longitude/:latitude', :controller => 'stores', :action => 'index' This works for integer latitude and longitude values (http://localhost:3000/stores/near/-88/49) but fails for decimal values (http://localhost:3000/stores/near/-88.341/49.123) giving: Routing Error No route matches "/stores/near/-88/49.0" with {:method=>:get} Any ideas how to use pretty URLs in rails with decimals?

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >