iOS
...
Data Objects
ParseGeoPoint 데이터 유형으로 지오쿼리 수행하기
8 분
지오쿼리 소개 우리는 지오쿼리 라는 용어를 사용하여 조건이 parsegeopoint parsegeopoint 유형 필드를 포함하는 쿼리 유형을 지칭합니다 back4app 데이터베이스에 지리적 위치 데이터를 저장하기 위해 parsegeopoint parsegeopoint 구조체를 사용하는 것이 좋습니다 parseswift sdk parseswift sdk 는 parsegeopoint parsegeopoint 데이터 유형에 적용된 조건에 따라 데이터를 쿼리할 수 있는 메서드 집합을 제공합니다 전제 조건 이 튜토리얼을 완료하려면 다음이 필요합니다 back4app에서 생성된 앱 쿼리를 테스트할 기본 ios 앱 목표 지리적 위치 데이터에 대한 조건을 사용하여 데이터를 쿼리하는 방법을 이해합니다 1 query\<u> 클래스에 대한 간단한 검토 back4app 데이터베이스에서 수행되는 모든 쿼리는 일반 클래스 query\<u> query\<u> 를 통해 이루어집니다 일반 매개변수 u u 는 우리가 데이터베이스에서 검색하려는 객체의 데이터 유형입니다 데이터 유형이 다음과 같을 때 myobject myobject , 우리는 다음과 같은 방법으로 back4app 데이터베이스에서 이러한 객체를 검색합니다 1 import parseswift 2 3 struct myobject parseobject { 4 5 } 6 7 let query = myobject query() 8 9 // executes the query asynchronously 10 query find { result in 11 // handle the result (of type result<\[myobject], parseerror>) 12 } 다음에 대한 자세한 내용을 읽을 수 있습니다 query\<u> query\<u> 클래스 공식 문서에서 여기 https //github com/parse community/parse swift 2 back4app에 데이터를 저장하기 쿼리를 실행하기 전에 back4app 데이터베이스에 샘플 데이터를 저장해야 합니다 빠른 시작 https //www back4app com/docs/ios/parse swift sdk/install sdk 가이드를 따르면 샘플 ios 앱을 back4app 데이터베이스에 구성하고 연결할 수 있습니다 이 가이드에서는 도시 정보를 저장할 것입니다 도시 정보를 정리하기 위해 다음 구조체를 사용합니다 1 import parseswift 2 3 struct city parseobject { 4 5 6 var name string? // city's name 7 var location parsegeopoint? // it will store the city's coordinate on earth 8 } 이제 샘플 데이터를 저장하는 단계로 진행합니다 이 단계는 swift 또는 앱의 콘솔 https //www youtube com/watch?v=nvwryrzbcma 을 사용하여 back4app 플랫폼에서 직접 구현할 수 있습니다 //after setting up your xcode project, calling the following method should save some sample data on your back4app database 1 import parseswift 2 3 func setupsampledata() { 4 do { 5 // montevideo uruguay 6 = try city( 7 name "montevideo", 8 location parsegeopoint(coordinate cllocationcoordinate2d(latitude 34 85553195363169, longitude 56 207280375137955)) 9 ) save() 10 11 // brasília brazil 12 = try city( 13 name "brasília", 14 location parsegeopoint(coordinate cllocationcoordinate2d(latitude 15 79485821477289, longitude 47 88391074690196)) 15 ) save() 16 17 // bogotá colombia 18 = try city( 19 name "bogotá", 20 location parsegeopoint(coordinate cllocationcoordinate2d(latitude 4 69139880891712, longitude 74 06936691331047)) 21 ) save() 22 23 // mexico city mexico 24 = try city( 25 name "mexico city", 26 location parsegeopoint(coordinate cllocationcoordinate2d(latitude 19 400977162618933, longitude 99 13311378164776)) 27 ) save() 28 29 // washington, d c united states 30 = try city( 31 name "washington, d c ", 32 location parsegeopoint(coordinate cllocationcoordinate2d(latitude 38 930727220189944, longitude 77 04626261880388)) 33 ) save() 34 35 // ottawa canada 36 = try city( 37 name "ottawa", 38 location parsegeopoint(latitude 45 41102167733425, longitude 75 695414598736) 39 ) save() 40 } catch let error as parseerror { 41 print("\[parseswift error]", error message) 42 } catch { 43 print("\[error]", error localizeddescription) 44 } 45 } back4app's console //a quick way to insert elements on your back4app database is via the console located in your app’s api section once you are there, you can start running javascript code to save the sample data 1 // add city objects and create table 2 // note how geopoints are created, passing latitude and longitude as arguments 3 // montevideo 4 city = new parse object('city'); 5 city set('name', 'montevideo uruguay'); 6 city set('location', new parse geopoint( 34 85553195363169, 56 207280375137955)); 7 await city save(); 8 9 // brasília 10 city = new parse object('city'); 11 city set('name', 'brasília brazil'); 12 city set('location', new parse geopoint( 15 79485821477289, 47 88391074690196)); 13 await city save(); 14 15 // bogotá 16 city = new parse object('city'); 17 city set('name', 'bogotá colombia'); 18 city set('location', new parse geopoint(4 69139880891712, 74 06936691331047)); 19 await city save(); 20 21 // mexico city 22 city = new parse object('city'); 23 city set('name', 'mexico city mexico'); 24 city set('location', new parse geopoint(19 400977162618933, 99 13311378164776)); 25 await city save(); 26 27 // washington, d c 28 city = new parse object('city'); 29 city set('name', 'washington, d c usa'); 30 city set('location', new parse geopoint(38 930727220189944, 77 04626261880388)); 31 await city save(); 32 33 // ottawa 34 city = new parse object('city'); 35 city set('name', 'ottawa canada'); 36 city set('location', new parse geopoint(45 41102167733425, 75 695414598736)); 37 await city save(); 3 데이터 쿼리하기 결과 정렬하기 샘플 데이터가 저장되었으므로, 다양한 쿼리 유형을 수행할 수 있습니다 첫 번째 예제로, 모든 도시를 선택하고 기준 지점에서 얼마나 떨어져 있는지에 따라 정렬할 것입니다 우리는 query\<city> query\<city> 객체에 제약 조건을 전달하여 이 쿼리를 구현합니다 near(key\ geopoint ) near(key\ geopoint ) 메서드는 parseswift sdk parseswift sdk 를 통해 사용할 수 있으며, 이러한 제약 조건을 구성할 수 있습니다 인수로는 기준 key key 의 이름(일반적으로 geopoint geopoint 로 언급됨)을 전달합니다 1 // the reference geopoint will be kingston city jamaica 2 guard let kingstongeopoint = try? parsegeopoint(latitude 18 018086950599134, longitude 76 79894232253473) else { return } 3 4 let query = city query(near(key "location", geopoint kingstongeopoint)) // the method near(key\ geopoint ) returns the constraint needed to sort the query 5 6 let sortedcities \[city]? = try? query find() // executes the query synchronosuly and returns an array containing the cities properly sorted 7 8 query find { result in // executes the query asynchronosuly and returns a result<\[city], parseerror> type object to handle the results 9 switch result { 10 case success(let cities) 11 // cities = \[bogotá, washington dc, mexico city, ottawa, brasília, montevideo] 12 case failure(let error) 13 // handle the error if something happened 14 } 15 } 주어진 지역 내에서 결과 선택하기 특정 지역 내에서 도시를 선택하고 싶다고 가정해 보겠습니다 우리는 withinkilometers(key\ geopoint\ distance ) withinkilometers(key\ geopoint\ distance ) 메서드로 생성된 제약 조건을 사용하여 이를 달성할 수 있습니다 인수로는 도시의 위치를 포함하는 필드의 이름, 지역의 중심( parsegeopoint parsegeopoint 데이터 유형) 및 이 지역의 중심에서 도시가 최대 얼마만큼 떨어질 수 있는지( km )를 전달합니다 자메이카 킹스턴에서 최대 3000km 떨어진 모든 도시를 선택하려면 다음과 같이 할 수 있습니다 1 let distance double = 3000 // km 2 guard let kingstongeopoint = try? parsegeopoint(latitude 18 018086950599134, longitude 76 79894232253473) else { return } 3 4 let query = city query(withinkilometers(key "location", geopoint kingstongeopoint, distance distance)) 5 // the method withinkilometers(key\ geopoint\ distance ) returns the constraint we need for this case 6 7 let sortedcities \[city]? = try? query find() // executes the query synchronosuly and returns an array containing the cities we are looking for (bogotá, washington dc and mexico city in this case) 8 9 query find { result in // executes the query asynchronosuly and returns a result<\[city], parseerror> type object to handle the results 10 switch result { 11 case success(let cities) 12 // cities = \[bogotá, washington dc, mexico city] 13 case failure(let error) 14 // handle the error if something happened 15 } 16 } 또한, 거리가 킬로미터 대신 마일로 주어질 때, 우리는 withinmiles(key\ geopoint\ distance\ sorted ) withinmiles(key\ geopoint\ distance\ sorted ) 메서드를 사용할 수 있습니다 덜 일반적인 방법인 withinradians(key\ geopoint\ distance\ sorted ) withinradians(key\ geopoint\ distance\ sorted ) , 는 거리가 라디안으로 주어질 경우에도 사용할 수 있습니다 그 사용법은 이전 방법들과 매우 유사합니다 주어진 다각형 내에서 결과 선택하기 이전 예제에서는 원형 지역으로 표현된 지역 내의 도시를 선택했습니다 만약 우리가 비원형 모양의 지역이 필요하다면, parseswift sdk parseswift sdk 는 꼭짓점으로부터 그러한 지역을 구성할 수 있도록 해줍니다 이 예제의 목표는 다섯 개의 정점으로 이루어진 다각형 내의 도시를 선택하는 것입니다 이러한 정점은 parsegeopoint parsegeopoint 구조체를 사용하여 표현됩니다 정점을 생성한 후, 우리는 parsepolygon parsepolygon 을 인스턴스화합니다 이 다각형은 withinpolygon(key\ polygon ) withinpolygon(key\ polygon ) 메서드( parseswift sdk parseswift sdk )에 전달되어 이 다각형 내의 도시를 선택할 수 있는 제약 조건을 구성합니다 1 // the polygon where the selected cities are 2 let polygon parsepolygon? = { 3 do { 4 // we first instantiate the polygon vertices 5 let geopoint1 = try parsegeopoint(latitude 15 822238344514378, longitude 72 42845934415942) 6 let geopoint2 = try parsegeopoint(latitude 0 7433770196268968, longitude 97 44765968406668) 7 let geopoint3 = try parsegeopoint(latitude 59 997149373299166, longitude 76 52969196322749) 8 let geopoint4 = try parsegeopoint(latitude 9 488786415007201, longitude 18 346101586021952) 9 let geopoint5 = try parsegeopoint(latitude 15 414859532811047, longitude 60 00625459569375) 10 11 // next we compose the polygon 12 return try parsepolygon(\[geopoint1, geopoint2, geopoint3, geopoint4, geopoint5]) 13 } catch let error as parseerror { 14 print("failed to instantiate vertices \\(error message)") 15 return nil 16 } catch { 17 print("failed to instantiate vertices \\(error localizeddescription)") 18 return nil 19 } 20 }() 21 22 guard let safepolygon = polygon else { return } 23 24 let query = city query(withinpolygon(key "location", polygon safepolygon)) 25 // withinpolygon(key\ polygon ) returns the required constraint to apply on the query 26 27 let cities = try? query find() // executes the query synchronously 28 29 query find { result in // executes the query asynchronously and returns a result of type result<\[], parseerror> 30 // handle the result 31 } 결론 요즘 맞춤형 서비스를 제공하기 위해 위치 데이터에 대한 작업을 수행하는 것이 매우 중요합니다 back4app은 parseswift sdk parseswift sdk 와 함께 이러한 작업을 쉽게 구현할 수 있도록 합니다