@@ -10,14 +10,19 @@ function getAgent() {
10
10
return cacheAgent ;
11
11
}
12
12
13
- async function fetchGeocoordinateFromBrazilLocation ( { state, city, street } ) {
13
+ async function fetchGeocoordinateFromBrazilLocation ( {
14
+ state,
15
+ city,
16
+ street,
17
+ cep,
18
+ } ) {
14
19
const agent = getAgent ( ) ;
15
20
const encodedState = encodeURI ( state ) ;
16
21
const encodedCity = encodeURI ( city ) ;
17
22
const encodedStreet = encodeURI ( street ) ;
18
23
19
24
const country = 'Brasil' ;
20
- const queryString = `format=json&addressdetails=1&country=${ country } &state=${ encodedState } &city=${ encodedCity } &street=${ encodedStreet } &limit=1 ` ;
25
+ const queryString = `format=json&addressdetails=1&country=${ country } &state=${ encodedState } &city=${ encodedCity } &street=${ encodedStreet } ` ;
21
26
22
27
const response = await fetch (
23
28
`https://nominatim.openstreetmap.org/search/?${ queryString } ` ,
@@ -26,15 +31,26 @@ async function fetchGeocoordinateFromBrazilLocation({ state, city, street }) {
26
31
27
32
const jsonData = await response . json ( ) ;
28
33
29
- if ( jsonData . length > 0 ) {
30
- const { lat : latitude , lon : longitude } = jsonData [ 0 ] ;
31
- return { type : 'Point' , coordinates : { longitude, latitude } } ;
34
+ const cleanedCep = cep . replace ( / \D / g, '' ) ;
35
+ const exactLocation = jsonData . find (
36
+ ( item ) => item . address . postcode . replace ( / \D / g, '' ) === cleanedCep
37
+ ) ;
38
+ const approximateLocation = jsonData . find (
39
+ ( item ) =>
40
+ item . address . postcode . replace ( / \D / g, '' ) . slice ( 0 , 5 ) ===
41
+ cleanedCep . slice ( 0 , 5 )
42
+ ) ;
43
+ const location = exactLocation || approximateLocation ;
44
+
45
+ if ( ! location ) {
46
+ return {
47
+ type : 'Point' ,
48
+ coordinates : { longitude : undefined , latitude : undefined } ,
49
+ } ;
32
50
}
33
51
34
- return {
35
- type : 'Point' ,
36
- coordinates : { longitude : undefined , latitude : undefined } ,
37
- } ;
52
+ const { lat : latitude , lon : longitude } = location ;
53
+ return { type : 'Point' , coordinates : { longitude, latitude } } ;
38
54
}
39
55
40
56
export default fetchGeocoordinateFromBrazilLocation ;
0 commit comments