【问题标题】:getting lat/long coordinates from firebase/firestore collection从 firebase/firestore 集合中获取 lat/long 坐标
【发布时间】:2019-12-11 12:24:48
【问题描述】:

我对原生和 firebase 的反应相对较新,如果有人能帮助我解决这个问题,那就太棒了。目前,当我向我的 firebase 收藏添加新帖子时,我会使用平面列表显示所有帖子,并且效果很好。但是是否可以只获取我的标记的 currentLatitude 和 currentLongitude ?我的目标是为每个帖子生成一个新标记。

Events = []


this.firestore.collection("Events").get().then(snapshot => {
  snapshot.forEach(doc => {
    Events.push(doc.data())
  })
})


    render() {
        return (
            <SafeAreaView style={{ flex: 1 }}>
                <View style={{ flex: 1 }}>
                    <MapView 
                        provider={PROVIDER_GOOGLE} 
                        mapType='hybrid'   
                        showsUserLocation style={{flex: 1}}>
                    <MapView.Marker
                        coordinate={{latitude: //currentLatitude,                         
                        longitude: //currntLongitude}}
                        title={("Test")}
                        description={("Test")} 
                    />               
                    </MapView>
                </View>
            </SafeAreaView>
        );
    }
}

【问题讨论】:

  • 你的意思是“是否有可能只为我的标记获取 currentLatitude 和 currentLongitude?”你的应用程序中应该有什么最终结果?
  • 感谢您回复@DevAS!我需要从我的 Firestore 文档中获取经纬度坐标,以将它们放入标记组件中。最终结果应该是存储在我的 Firestore 中的每个文档/帖子的标记。例如 airbnb。
  • 那么问题出在哪里?正如我在最后一张图片中看到的那样,你得到了经纬度,然后你将它传递给标记!您在地图上看到的应该是位置标记
  • 如果你有一些最终结果的 gif 或图像,这将有助于理解你想要实现的目标

标签: firebase react-native google-cloud-firestore react-native-maps


【解决方案1】:

@DevAS 感谢您的耐心。这是由 3 个不同的 .js 文件组成的。但我现在不知道如何将它放入 map.js 中。

最终结果应如下所示: enter image description here

除了 lat/lng 线之外的所有东西都应该在标注窗口中。

Item.js:

import { Ionicons } from '@expo/vector-icons';
import React from 'react';
import { Image, StyleSheet, Text, View } from 'react-native';
import Fire from '../screens/Fire'


const profileImageSize = 36;
const padding = 12;

export default class Item extends React.Component {
  state = {
    user: {}
  };

  componentDidMount() {

    const user = this.props.uid || Fire.shared.uid;

    this.unsubscribe = Fire.shared.firestore
        .collection("users")
        .doc(user)
        .onSnapshot(doc => {
            this.setState({ user: doc.data() });
        });


    if (!this.props.imageWidth) {
      // Get the size of the web image
      Image.getSize(this.props.image, (width, height) => {
        this.setState({ width, height });
      });
    }
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  render() {
    const { title, address, name, imageWidth, imageHeight, image, currentLatitude, currentLongitude } = this.props;

    // Reduce the name to something
    const imgW = imageWidth || this.state.width;
    const imgH = imageHeight || this.state.height;
    const aspect = imgW / imgH || 1;

    return (
      <View>
        <Header image={{ uri: this.state.user.avatar }} name={this.state.user.name} />
        <Image
          resizeMode="contain"
          style={{
            backgroundColor: "#D8D8D8",
            width: "100%",
            aspectRatio: aspect
          }}
          source={{ uri: image }}
        />
        <Metadata 
        name={this.state.user.name} 
        address={address}
        title={title}
        currentLongitude={currentLongitude}
        currentLatitude={currentLatitude}
        />
      </View>
    );
  }
}

const Metadata = ({ name, address, title, currentLongitude, currentLatitude}) => (
  <View style={styles.padding}>
    <IconBar />
    <Text style={styles.text}>{name}</Text>
    <Text style={styles.subtitle}>{address}</Text>
    <Text style={styles.subtitle}>{title}</Text>  
    <Text style={styles.subtitle}>Lat: {currentLatitude}</Text> 
    <Text style={styles.subtitle}>Lng: {currentLongitude}</Text> 
  </View>
);

const Header = ({ name, image }) => (
  <View style={[styles.row, styles.padding]}>
    <View style={styles.row}>
      <Image style={styles.avatar} source={image} />
      <Text style={styles.text}>{name}</Text>
    </View>
    <Icon name="ios-more" />
  </View>
);

const Icon = ({ name }) => (
  <Ionicons style={{ marginRight: 8 }} name={name} size={26} color="black" />
);

const IconBar = () => (
  <View style={styles.row}>
    <View style={styles.row}>
      <Icon name="ios-heart-empty" />
      <Icon name="ios-chatbubbles" />
      <Icon name="ios-send"/>
    </View>
    <Icon name="ios-bookmark" />
  </View>
);

const styles = StyleSheet.create({
  text: { fontWeight: "600" },
  subtitle: {
    opacity: 0.8
  },
  row: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center"
  },
  padding: {
    padding
  },
  avatar: {
    aspectRatio: 1,
    backgroundColor: "#D8D8D8",
    borderWidth: StyleSheet.hairlineWidth,
    borderColor: "#979797",
    borderRadius: profileImageSize / 2,
    width: profileImageSize,
    height: profileImageSize,
    resizeMode: "cover",
    marginRight: padding
  }
});

List.js

import React from 'react';
import { FlatList } from 'react-native';

import Footer from './Footer';
import Item from './Item';

class List extends React.Component {
  renderItem = ({ item }) => <Item {...item} />;
  keyExtractor = item => item.key;
  render() {
    const { onPressFooter, ...props } = this.props;
    return (
      <FlatList
        keyExtractor={this.keyExtractor}
        ListFooterComponent={footerProps => (
          <Footer {...footerProps} onPress={onPressFooter} />
        )}
        renderItem={this.renderItem}
        {...props}
      />
    );
  }
}
export default List;

FeedScreen.js

import firebase from "firebase";
import React, { Component } from "react";
import { LayoutAnimation, RefreshControl } from "react-native";

import List from "../components/List";
import Fire from "./Fire";

// Set the default number of images to load for each pagination.
const PAGE_SIZE = 5;
console.disableYellowBox = true;
export default class FeedScreen extends Component {
  state = {
    loading: false,
    data: {}
  };

  componentDidMount() {
    // Check if we are signed in...
    if (Fire.shared.uid) {
      // If we are, then we can get the first 5 posts
      this.makeRemoteRequest();
    } else {
      // If we aren't then we should just start observing changes. This will be called when the user signs in
      firebase.auth().onAuthStateChanged(user => {
        if (user) {
          this.makeRemoteRequest();
        }
      });
    }
  }

  // Append the item to our states `data` prop
  addPosts = posts => {
    this.setState(previousState => {
      let data = {
        ...previousState.data,
        ...posts
      };
      return {
        data,
        // Sort the data by timestamp
        posts: Object.values(data).sort((a, b) => a.timestamp < b.timestamp)
      };
    });
  };

  // Call our database and ask for a subset of the user posts
  makeRemoteRequest = async lastKey => {
    // If we are currently getting posts, then bail out..
    if (this.state.loading) {
      return;
    }
    this.setState({ loading: true });

    // The data prop will be an array of posts, the cursor will be used for pagination.
    const { data, cursor } = await Fire.shared.getPaged({
      size: PAGE_SIZE,
      start: lastKey
    });

    this.lastKnownKey = cursor;
    // Iteratively add posts
    let posts = {};
    for (let child of data) {
      posts[child.key] = child;
    }
    this.addPosts(posts);

    // Finish loading, this will stop the refreshing animation.
    this.setState({ loading: false });
  };

  // Because we want to get the most recent items, don't pass the cursor back.
  // This will make the data base pull the most recent items.
  _onRefresh = () => this.makeRemoteRequest();

  // If we press the "Load More..." footer then get the next page of posts
  onPressFooter = () => this.makeRemoteRequest(this.lastKnownKey);

  render() {
    // Let's make everything purrty by calling this method which animates layout changes.
    LayoutAnimation.easeInEaseOut();
    return (
      <List
        refreshControl={
          <RefreshControl
            refreshing={this.state.loading}
            onRefresh={this._onRefresh}
          />
        }
        onPressFooter={this.onPressFooter}
        data={this.state.posts}
      />
    );
  }
}

【讨论】:

    猜你喜欢
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多