Can anyone suggest a way to store a int value (extracted from firebase realtime DB) and store it to transfer it to MapRegion?

Please provide the following:

  1. SDK Version: 46
  2. Platforms(Android/iOS/web/all): Android/IOS

My code

import { StyleSheet, Text, View, Dimensions, Button } from 'react-native'
import React , {useEffect, useState} from 'react'
import {ref, onValue} from 'firebase/database'
import {db} from '../firebase'
import MapView, {Marker} from 'react-native-maps';
import * as Loc from 'expo-location';


const Location = ({route}) => {
  const paramKey = route.params.paramKey1
  console.log(paramKey)
  var ke, latit, longit;
  const [todoDatak, setToDoDatak] = useState([])
  
  const [todoDatal, setToDoDatal] = useState([])
  const [todoData2, setToDoData2] = useState([])

  const [mapRegion, setMapRegion] = useState({
    latitude: toDoData1,
    longitude: toDoData2,
    latitudeDelta: 0.9,
    longitudeDelta:0.9,
  })
  
  const [mapRegionNow, setMapRegionNow] = useState({
    latitude: 1.3483,
    longitude: 103.6831,
    latitudeDelta: 0.9,
    longitudeDelta:0.9,
  })
 

  
  useEffect (() => {
    const starCountRef = ref(db, "food/" + paramKey);
    onValue(starCountRef, (snapshot) =>{      
      latit = snapshot.val().Latitude
      longit = snapshot.val().Longitude
      ke = snapshot.key;
      setToDoDatak(ke)      
      setToDoDatal(latit)
      setToDoData2(longit)     
      });
      userLocation();
    }, [])
    console.log('Latitude = ' + todoDatal)
    console.log('Longitude = ' + todoData2)    
  return (

I cant seem to set the latitude and longitude from toDoData1 and toDoData2. I get the error of Value for latitude cannot be cast from ReadableNativeArray to Double

Can anyone suggest a idea on how do I solve the following? I am able to extract the latitude and longitude from my firebase realtime db but I cant put it for the map region’s latitude and longitude via toDoData1 and toDoData2.

The values I get via console logging:
enter image description here

It’s complaining about those values being arrays, and you’re initialising them to arrays.

Try initialising them to something else. e.g. like this, which will set them to undefined initially:

  const [todoDatal, setToDoDatal] = useState();
  const [todoData2, setToDoData2] = useState();

Also, you probably want to avoid trying to use those values on the map if they have not yet been set to the valid values.

Thanks for the quick reply and advice !
I have tried changing like what you have said:
From

const [todoDatal, setToDoDatal] = useState([])
const [todoData2, setToDoData2] = useState([])

To

const [todoDatal, setToDoDatal] = useState();
const [todoData2, setToDoData2] = useState();

But it is still not working. I get the following in my application:

To see if I have gotten the correct value from my firebase realtime DB and if I have store them properly in the variables, I edited the codes:

 useEffect (() => {
    const starCountRef = ref(db, "food/" + paramKey);
    onValue(starCountRef, (snapshot) =>{
 
      latit = snapshot.val().Latitude
      console.log("Value from Firebase: " + latit)
      longit = snapshot.val().Longitude
      console.log("Value from Firebase: " + longit);
      
      ke = snapshot.key;
      setToDoDatak(ke)
      
      setToDoDatal(latit)
      setToDoData2(longit)
     
      });
      userLocation();
    }, [])
    console.log('Latitude = ' + todoDatal)
    console.log('Longitude = ' + todoData2)

My console logs are the following:

The data seems to be able to be extracted and store in toDoData1 and toDoData2 but it just cannot be pass over to the MapRegion’s latitude and longitude. Am I missing a step in between?

Nowhere in the code you have posted is there any reference to coordinate (mentioned in the error message.) So I can’t see how you’re setting it and what you’re setting it to.

But I suspect you’re trying to use the latitude/longitude for the marker before they have a value.

You should instead not display the marker if the latitude and longitude are not yet set.

Here’s an old Stack Overflow question about the same issue:

The answers there initialize the latitude and longitude to 0. But that will initially put the marker off the coast of Africa:

Instead, you should do something like this:

{latitude && longitude && <Marker coordinate={{ longitude, latitude }} title={"my marker"}/>}

Then if latitude or longitude have not yet been set it will not try to show the marker.

1 Like

Hi,

I tried the following line

{latitude && longitude && <Marker coordinate={{ longitude, latitude }} title={"my marker"}/>}

But I have the error of ReferenceError: Can’t find variable: latitude

May I ask which longitude and longitude is this referring to? I am quite confuse at the moment.
I assume is the toDoData1 (Has the value of 1.34671) and toDoData2 (Has the value of 103.68066)

So I tried the following:

{toDoData1 && toDoData2 && <Marker coordinate={{ toDoData1, toDoData2 }} title={"my marker"}/>}

I get the same error (Screenshot of the app) in my previous comment.

I dont know if this will help or not but my intention on this page is to put 2 markers. 1 marker is for the current location (MapRegionNow) of the user using the app and the 2nd marker is for the destination (MapRegion). This destination, latitude and longitude values are extracted from firebase realtime database.

Sorry, I forgot you were using other variable names.

The problem with the above is that it will pass the a coordinate object to the marker that contains no latitude or longitude.

The following syntax:

{ longitude, latitude }

is shorthand for this:

{ longitude: longitude, latitude: latitude }

So your coordinate object above actually means:

{ toDoData1: toDoData1, toDoData2: toDoData2 }

Since your variables are not called longitude and latitude you will need:

{toDoData1 && toDoData2 && <Marker coordinate={{ latitude: toDoData1, longitude: toDoData2 }} title={"my marker"}/>}

The above code means “if toDoData1 and toDoData2 both contain something other than null, undefined or false then show the marker. Otherwise don’t show the marker.”

OK, basically you just need to make sure that your latitude and longitude values are valid when you render the <Marker />. If they are not valid then you can avoid rendering the marker as above.

1 Like

Oh! Finally it work. Thanks for the explanation and thank you very much ! I understand now but mind if I ask a few question regarding this mapview? I am new at this and I am still trying to learn.
Currently my code

const Location = ({route}) => {
  const paramKey = route.params.paramKey1
  //console.log(paramKey)
  var ke, latit, longit, la, lo;
  const [todoDatak, setToDoDatak] = useState([])
  
  const [todoDatal, setToDoDatal] = useState();
  const [todoData2, setToDoData2] = useState();

  
  
  const [mapRegion, setMapRegion] = useState({
    latitude: 1.3483,
    longitude: 103.6831,
    latitudeDelta: 0.09,
    longitudeDelta:0.09,
  })
  const [mapRegionNow, setMapRegionNow] = useState({
    latitude: 0,
    longitude: 0,
    latitudeDelta: 0.09,
    longitudeDelta:0.09,
  })
  const userLocation = async()=>{
    let { status } = await Loc.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
      }
      let location = await Loc.getCurrentPositionAsync({enableHighAccuracy:true});
      setMapRegionNow({
          latitude:location.coords.latitude,
          longitude:location.coords.longitude,
          latitudeDelta:0.09,
          longitudeDelta:0.09,
      });
      
      
      //console.log(location.coords.latitude, location.coords.longitude)
  }
  
  

  
  useEffect (() => {
    const starCountRef = ref(db, "food/" + paramKey);
    onValue(starCountRef, (snapshot) =>{
      
      
      
      latit = snapshot.val().Latitude
      console.log("Value from Firebase: " + latit)
      longit = snapshot.val().Longitude
      console.log("Value from Firebase: " + longit);
      
      ke = snapshot.key;
      setToDoDatak(ke)
      
      setToDoDatal(latit)
      setToDoData2(longit)
     
      });
      userLocation();
    }, [])
    console.log('Latitude = ' + todoDatal)
    console.log('Longitude = ' + todoData2)    
  return (
    <View style = {styles.container}>       
       <Text style = {styles.header}>Shop Name</Text>
       <Text style = {styles.text}>{todoDatak}</Text>
            
       <View style={styles.container}>
       
        <MapView style={styles.map} 
          region={mapRegion}
        >
          <Marker coordinate={mapRegionNow} pinColor={'purple'} title='Current Location'/>
          {todoDatal && todoData2 && <Marker coordinate={{ latitude: todoDatal, longitude: todoData2 }} title={"Destination"}/>}
          
          </MapView>
          <Button title= 'Get Location' onPress={userLocation}/>
          
      </View> 
    </View>    
  )
}

export default Location
  1. The MapRegionNow is for my current location. How do I make this marker for MapRegionNow appear after I click the button of Get Location . Because now it just appears in my screen without me clicking the button

  2. Is it possible to create a path between the 2 markers?

  1. You can set the initial lat/long to null instead of 0:
  const [mapRegionNow, setMapRegionNow] = useState({
    latitude: null,
    longitude: null,
    latitudeDelta: 0.09,
    longitudeDelta:0.09,
  })
  1. You can use a similar trick to avoid showing the marker before it has valid latitude/longitude set:
          {mapRegionNow.latitude && <Marker coordinate={mapRegionNow} pinColor={'purple'} title='Current Location'/>}
          {todoDatal && todoData2 && <Marker coordinate={{ latitude: todoDatal, longitude: todoData2 }} title={"Destination"}/>}

(You could check both lat and long, but one is enough.)

  1. You are calling userLocation() in the useEffect hook, so it will automatically do that without the user pressing the button:

If you remove that userLocation() call then it won’t run until the user presses the button.

Sorry, I don’t know. Actually all of your questions in this thread are unrelated to Expo :slight_smile: so this is not the best place to ask them. You should ask questions like this in a community dedicated to React Native Maps if there is one, or else a place like Stack Overflow.

1 Like

I actually tried to did the similar trick that you have suggested in the earlier problem but it just pop up with all sorts of new error that I never see before which is why I pop the question on this issue.

Regarding the 2nd issue, it’s okay ! Thanks for willing to help me on this, giving me a clear explanation for the issues that I am asking. Really, thanks a lot ! I’m very grateful for that. This is because I am a beginner in developing a app using expo, actually my first time and the documents can be overwhelming for me which is why I don’t understand some stuff despite referring to documents/youtube guides/forums.

Regarding about posting question like this, I thought this Expo Location is under Expo SDK according to API Reference - Expo Documentation at the left hand side under Expo SDK so I thought it should be okay to post under Expo SDK. I actually did tried posting on Stack Overflow about 12 hours ago to look for a way to solve the issues but no one reply. So I tried posting the issue here hoping someone can guide me into fixing the issue I am. So thank you very much !

1 Like

Yes, I understand :slight_smile: It takes a while to figure things out.

Yes, Expo Location is part of the Expo SDK, but your questions were not actually about that. Your questions were more about React and JavaScript than Expo Location. I understand that it might not always be easy to know for sure, especially if you’re a beginner.

Oh, and feel free to post your working code as an answer under your Stack Overflow question.

1 Like

Oh, sorry about it. So I guess it isnt allowed to post question of React and JavaScript here?

Okay

It’s not disallowed, but the purpose of these forums is to discuss things specific to Expo. If something is not specific to Expo then it’s best to discuss them elsewhere.

Unfortunately not every question is answered here. If your question is actually about JavaScript or React and not specifically about Expo then there is a lower chance that someone will spend time answering it. (Or that’s what I suspect.)

Oh okay. Thanks for the clarification ! I will take note of it. By any chance, are you good with firebase realtime database? I am having trouble and I need some help. javascript - Grabbing the wrong item from firebase realtime database via react native expo - Stack Overflow

I’ve never used it

Oh. Its okay then

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.