Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MapView addressForCoordinate method is throwing error as "Cannot read properties of undefined(reading apply)" #3955

Closed
sarulathadurai opened this issue Sep 16, 2021 · 18 comments
Labels

Comments

@sarulathadurai
Copy link

sarulathadurai commented Sep 16, 2021

Bug report

Summary

I am trying to get the address onPress event by passing the coordinates to addressForCooordinate method but it throws error.

Environment info

react-native info output:

      react-native: 0.64.2
      react: 17.0.1
      react-native-maps: ^0.29.0

Code

          <MapView
          ref = {mapRef}
          provider={PROVIDER_GOOGLE} 
          style={[styles.map,{flex:1}]}
          showsUserLocation={true}
          followsUserLocation={true}
          loadingEnabled={true}
          showsMyLocationButton={true}
          mapType="standard"
          initialRegion={
              {
                latitude:position.latitude,
                longitude:position.longitude, 
                latitudeDelta: 0.0922,
                longitudeDelta: 0.0421
                }
            }
            onPress={getAddress}
        >
        <MapView.Marker
            coordinate={{latitude:position.latitude,longitude:position.longitude}}
            pinColor="red"
            draggable
            onDragEnd={(event)=>{setCoordinates(event.nativeEvent.coordinate)}}
        />

        </MapView>
 const getAddress = (e) => {
    mapRef.current.addressForCoordinate(e.nativeEvent.coordinate)
    .then((address) => {
      console.log('address', address); 
    }).catch((err) => {
      console.log('err', err); 
    })
  }

According to readme it should return promise with resolved address but
throws error as
Simulator Screen Shot - iPhone 12 - 2021-09-16 at 12 27 40

@sarulathadurai sarulathadurai added the bug Something isn't working label Sep 16, 2021
@christopherdro
Copy link
Collaborator

@mechazod Any ideas?

@mechazod
Copy link
Contributor

@sarulathadurai, please use onRegionChangeComplete #3911 (comment)

@sarulathadurai
Copy link
Author

@mechazod same error is thrown

@huangzichenzuishuaile
Copy link

@sarulathadurai Have you solved this problem? I have the same problem now

@huangzichenzuishuaile
Copy link

@mechazod Have you solved this problem? I have the same problem now

@danieldanielecki
Copy link

danieldanielecki commented Oct 28, 2021

#3911 (comment) isn't helpful for me either. The mapRef.current.addressForCoordinate returns TypeError: undefined is not an object (evaluating 'this.mapRef.current.addressForCoordinate').

Only mapRef.addressForCoordinate without current returns something meaningful, i.e., Invariant Violation: No callback found with cbID 12730 and callID 6365 for AIRMapManager.getAddressFromCoordinates - most likely the callback was already invoked. Args: '[{"locality":"Katwijk","subThoroughfare":"7A","subLocality":"(null)","postalCode":"2225 PA","administrativeArea":"South Holland","country":"Netherlands","subAdministrativeArea":"Katwijk","thoroughfare":"Bestevaerweg","countryCode":"NL","name":"Bestevaerweg 7A"}]', but that's still an exception...

It's all in onLongPress, becauase onRegionChangeComplete, as suggested in #3911 (comment), doesn't work. The onRegionChangeComplete returns TypeError: undefined is not an object (evaluating 'e.nativeEvent.coordinate') in both scenarios, with current, and without.

method.ts

export default async function getAddressFromCoordinate(this: any, e: any) {
  if (this.mapRef) {
    const { latitude, longitude } = e.nativeEvent.coordinate;
    await this.mapRef
      .addressForCoordinate({ latitude, longitude })
      .then((address: any) => {
        console.log("address", address);
      })
      .catch((err: Error) => {
        console.log("err", err);
      });
  }
}

component.tsx

<MapView
  onLongPress={async (e) => await getAddressFromCoordinate(e)}
  ref={(ref) => (this.mapRef = ref)}
>

@danieldanielecki
Copy link

@sarulathadurai, please reopen this issue, so the issue is visible in the issues.

Similarly, #3775 #3850 #3854 #3911 should stay open as well.

@sarulathadurai
Copy link
Author

@sarulathadurai Have you solved this problem? I have the same problem now

No not yet

@00frank
Copy link

00frank commented Nov 25, 2021

Nothing to do with this issue, but a workaround solution could be using a reverse geolocation api.
If you are developing this for a really small project or demo, you can use free Open Cage API and a the function could be exported like this, up to the devs add/merge/fix this package functionality.

import env from "../env.json" // your private api keys / tokens

export default async function (coords) {
  let { latitude, longitude } = coords;
  let resp = await fetch(`https://api.opencagedata.com/geocode/v1/json?q=${latitude}+${longitude}&key=${env.geolocationServiceAPIKey}`)
  let data = await resp.json();

  return data.results[0] // this gets location info such as country, state, city, address...
}

@X0GT0X
Copy link

X0GT0X commented Feb 4, 2022

I have the same issue when using mapRef.current.addressForCoordinate inside the onPress callback for getting the address from coordinate. Have anyone got any solution for this to make it work on iOS? Using the another geo api is not a solution for me at all.

Simulator Screen Shot - iPhone 13 - 2022-02-04 at 17 56 41

@danieldanielecki
Copy link

Not really, looks like a big issue :(

@bruno-de-queiroz
Copy link

For those in need, if you don't use google as map provider it will work on iOS

@danieldanielecki
Copy link

@bruno-de-queiroz can you share your code?
I've been debugging on iOS and same effect.

@monholm
Copy link
Collaborator

monholm commented Mar 13, 2022

This is more a missing feature and a lack of documentation, than a bug. addressForCoordinate isn't implemented for provider={"google"} on iOS.

@bruno-de-queiroz the following works on both Android and iOS, but not when using Google Maps on iOS.

import React, {useRef} from 'react';
import {StyleSheet} from 'react-native';
import MapView, {Region} from 'react-native-maps';

export default function App() {
  const mapRef = useRef<MapView>(null);

  const regionChangeCompleteHandler = async ({latitude, longitude}: Region) => {
    console.log(
      await mapRef.current?.addressForCoordinate({
        latitude,
        longitude,
      }),
    );
  };

  return (
    <MapView
      ref={mapRef}
      style={styles.mapView}
      onRegionChangeComplete={regionChangeCompleteHandler}
    />
  );
}

const styles = StyleSheet.create({
  mapView: {
    flex: 1,
  },
});

If anyone could open a pull request to clearly state in the docs that addressForCoordinate is Android and Apple Maps only, that would be extremely helpful.
Also, if anyone could put together a new issue as a feature request, requesting this functionality for Google Maps on iOS? That will leave us with a much better chance of somebody picking up the task.

@faycal-dev

This comment was marked as off-topic.

@github-actions
Copy link

🎉 This issue has been resolved in version 0.31.0-beta.1 🎉

The release is available on:

Your semantic-release bot 📦🚀

@github-actions
Copy link

🎉 This issue has been resolved in version 0.31.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@pejak4
Copy link

pejak4 commented Nov 10, 2023

This isn't solved in version react-native-maps": "^1.7.1. Its working on Android but on iOS it still throws error Cannot read properties of undefined (reading 'apply').

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests