Javascript 动态渲染MapView标记

Javascript 动态渲染MapView标记,javascript,reactjs,react-native,Javascript,Reactjs,React Native,这是我的地图视图的外观: <MapView style={styles.mapStyle} initialRegion={{ latitude: 51.524300, longitude: -0.037790, latitudeDelta: 0.0122, longitudeDelta: 0.0421

这是我的地图视图的外观:

<MapView
                style={styles.mapStyle}
                initialRegion={{
                latitude: 51.524300,
                longitude: -0.037790,
                latitudeDelta: 0.0122,
                longitudeDelta: 0.0421,


            }}
            >
            <Marker
                coordinate={{
                    latitude:51.524464,
                    longitude:-0.036285,
                    latitudeDelta:0.0,
                    longitudeDelta:0.0
                }}
                title={"Marker 1"}
                description={customData.text1} 
            />
            <Marker
                coordinate={{
                    latitude:51.524310,
                    longitude:-0.037798,
                    latitudeDelta:0.0,
                    longitudeDelta:0.0
                }}
                title={"Marker 2"}
                description={customData.text2}
            />
            <Marker
                coordinate={{
                    latitude:51.523174,
                    longitude:-0.039332,
                    latitudeDelta:0.0,
                    longitudeDelta:0.0
                }}
                title={"Marker 3"}
                description={customData.text3}
            />

            </MapView>

如您所见,我硬编码了3个标记,以确保地图视图正常工作。现在,我使用一个外部API,它根据用户的输入告诉停车位。例如,如果用户输入某个邮政编码/邮政编码,api将返回一个数组,其中包含关于停车位的各种信息,如经度和纬度。我想在地图上用标记来表示这些停车位。我使用了一个平面列表:

<FlatList
                data = {parkingSpaces}
                renderItem={({ item }) => {
                    return <MapView.Marker
                    coordinate={{
                    latitude: parseInt(item.latitude),
                    longitude:parseInt(item.longitude)
                    }}

                    title = {"parking markers"}

                    />  

                }}
                keyExtractor={item => item.unique_identifier}

            />
{
返回
}}
keyExtractor={item=>item.unique_identifier}
/>
我没有发现任何错误,但是我看不到地图上的标记。下面是我的全部代码

import React ,{Component,useState,useEffect} from 'react'
import {View,Text,StyleSheet,Dimensions,Button,Alert,FlatList} from 'react-native'
import MapView , {Marker}from 'react-native-maps'
import axios from 'axios'
import { TextInput } from 'react-native-gesture-handler'
import camdenParking from '../api/camdenParking'
import SearchBar from '../components/SearchBar'



/// Key Secret : 5ulg30lagu2o493uwsmn24rxklsg0ivb05k2zl6xqhiz8js9e7
/// App Secret Token : NTEX14nQLbrS8MIz4RmC6riUV6K2aQ_j687H


const HomeScreen = ()=>

{

    const [parkingSpaces,setparkingSpaces] = useState([])
    const[term,setTerm] = useState('')
    let userLatitude = 0
    let userLongitude = 0 

    const customData = require("./MarkersText.json")


      const searchApi = async() => {

        const response = await camdenParking.get("",{

            params:{
                //longitude:-0.115444,
                //latitude:51.517597
                postcode: term


            }

        }) // you can change this later on
        console.log(response.data)
        setparkingSpaces(response.data)
        console.log(term)      
      }


      const findCoordinates = () => {
        navigator.geolocation.getCurrentPosition(
          position => {
            const locationString = JSON.stringify(position); // Here we get the JSON object but it needs to be parsed
            var longLat = JSON.parse(locationString); // Here we parse the JSON object

             userLatitude=longLat.coords.latitude
             userLongitude=longLat.coords.longitude

             console.log(userLatitude) // This prints the current latitude from the user
             console.log(userLongitude) // This prints the longitude



          },
          error => Alert.alert(error.message),
          { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 }
        );
      };


     //useEffect(()=>{
       // searchApi()
     //},[])



    return(


        <View style={styles.container}>
            <SearchBar 
                term={term}
                onTermChange={newTerm=>setTerm(newTerm)}
                onTermSubmit={()=> searchApi(term)}
                />
            <MapView
                style={styles.mapStyle}
                initialRegion={{
                latitude: 51.524300,
                longitude: -0.037790,
                latitudeDelta: 0.0122,
                longitudeDelta: 0.0421,


            }}
            >
            <Marker
                coordinate={{
                    latitude:51.524464,
                    longitude:-0.036285,
                    latitudeDelta:0.0,
                    longitudeDelta:0.0
                }}
                title={"Marker 1"}
                description={customData.text1} 
            />
            <Marker
                coordinate={{
                    latitude:51.524310,
                    longitude:-0.037798,
                    latitudeDelta:0.0,
                    longitudeDelta:0.0
                }}
                title={"Marker 2"}
                description={customData.text2}
            />
            <Marker
                coordinate={{
                    latitude:51.523174,
                    longitude:-0.039332,
                    latitudeDelta:0.0,
                    longitudeDelta:0.0
                }}
                title={"Marker 3"}
                description={customData.text3}
            />

            </MapView>
            <Text>We have found {parkingSpaces.length} results</Text>
            <Button onPress={searchApi} title=" Click Here To Get Parking Spaces" />
            <Button onPress={findCoordinates} title=" Click Here To Get User's Location" />
            <Text>Parking Spaces found around {term}</Text>

            <FlatList
                data = {parkingSpaces}
                renderItem={({ item }) => {
                    return <MapView.Marker
                    coordinate={{
                    latitude: parseInt(item.latitude),
                    longitude:parseInt(item.longitude)
                    }}

                    title = {"parking markers"}

                    />  

                }}
                keyExtractor={item => item.unique_identifier}

            />

            <FlatList 
                data = {parkingSpaces}
                renderItem={({ item }) => {
                    return <Text> {item.road_name} | Possible Available Spaces:{item.parking_spaces} </Text>

                }}
            keyExtractor={item => item.unique_identifier}

            />


        </View>
    );
};

const styles = StyleSheet.create(
    {
     container:{
         flex:1,
         backgroundColor: '#fff',
         //alignItems: 'center',
         //justifyContent: 'center',
         //...StyleSheet.absoluteFillObject,
         //marginLeft:0,
         //height:400,
         //width:400,
         //justifyContent:"flex-end",
         //alignItems:"center",   
     },

     mapStyle: {
        width: 400,
        height:400, 
        //width: Dimensions.get('window').width,
        //height: Dimensions.get('window').height,
      },
    }

)

export default HomeScreen
import React,{Component,useState,useffect}来自'React'
从“react native”导入{视图、文本、样式表、维度、按钮、警报、平面列表}
从“react native maps”导入MapView,{Marker}
从“axios”导入axios
从“反应本机手势处理程序”导入{TextInput}
从“../api/camdenParking”导入camdenParking
从“../components/SearchBar”导入搜索栏
///关键机密:5ulg30lagu2o493uwsmn24rxklsg0ivb05k2zl6xqhiz8js9e7
///应用程序秘密令牌:NTEX14NQLBRS84RMC6RIUV6K2AQ_j687H
常量主屏幕=()=>
{
常量[ParkingSpace,SetParkingSpace]=useState([])
const[term,setTerm]=useState(“”)
让userLatitude=0
让userLongitude=0
const customData=require(“./MarkersText.json”)
const searchApi=async()=>{
const response=等待camdenParking.get(“”{
参数:{
//经度:-0.115444,
//纬度:51.517597
邮政编码:term
}
})//您可以稍后更改此选项
console.log(response.data)
设置停车空间(response.data)
console.log(术语)
}
常量findCoordinates=()=>{
navigator.geolocation.getCurrentPosition(
位置=>{
const locationString=JSON.stringify(position);//这里我们得到了JSON对象,但需要对其进行解析
var longLat=JSON.parse(locationString);//这里我们分析JSON对象
userLatitude=longLat.coords.latitude
userLongitude=longLat.coords.longitude
log(userLatitude)//这将从用户打印当前纬度
log(userLongitude)//这将打印经度
},
error=>Alert.Alert(error.message),
{enableHighAccurance:false,超时:20000,最大值:1000}
);
};
//useffect(()=>{
//searchApi()
//},[])
返回(
setTerm(newTerm)}
onTermSubmit={()=>searchApi(术语)}
/>
我们找到了{parkingspace.length}结果
在{term}周围找到停车位
{
返回
}}
keyExtractor={item=>item.unique_identifier}
/>
{
返回{item.road_name}可能的可用空间:{item.parking_Spaces}
}}
keyExtractor={item=>item.unique_identifier}
/>
);
};
const styles=StyleSheet.create(
{
容器:{
弹性:1,
背景颜色:“#fff”,
//对齐项目:“居中”,
//为内容辩护:“中心”,
//…StyleSheet.absoluteFillObject,
//marginLeft:0,
//身高:400,
//宽度:400,
//辩护内容:“柔性端”,
//对齐项目:“中心”,
},
地图样式:{
宽度:400,
身高:400,
//宽度:尺寸。获取('窗口')。宽度,
//高度:尺寸。获取(“窗口”)。高度,
},
}
)
导出默认主屏幕
更新

这就是我的代码现在的样子:

import React ,{Component,useState,useEffect} from 'react'
import {View,Text,StyleSheet,Dimensions,Button,Alert,FlatList} from 'react-native'
import MapView , {Marker}from 'react-native-maps'
import axios from 'axios'
import { TextInput } from 'react-native-gesture-handler'
import camdenParking from '../api/camdenParking'
import SearchBar from '../components/SearchBar'



/// Key Secret : 5ulg30lagu2o493uwsmn24rxklsg0ivb05k2zl6xqhiz8js9e7
/// App Secret Token : NTEX14nQLbrS8MIz4RmC6riUV6K2aQ_j687H


const HomeScreen = ()=>

{

    const [parkingSpaces,setparkingSpaces] = useState([])
    const[term,setTerm] = useState('')
    let userLatitude = 0
    let userLongitude = 0 

    const customData = require("./MarkersText.json")


      const searchApi = async() => {

        const response = await camdenParking.get("",{

            params:{
                //longitude:-0.115444,
                //latitude:51.517597
                postcode: term


            }

        }) // you can change this later on
        console.log(response.data)
        setparkingSpaces(response.data)
        console.log(term)      
      }


      const findCoordinates = () => {
        navigator.geolocation.getCurrentPosition(
          position => {
            const locationString = JSON.stringify(position); // Here we get the JSON object but it needs to be parsed
            var longLat = JSON.parse(locationString); // Here we parse the JSON object

             userLatitude=longLat.coords.latitude
             userLongitude=longLat.coords.longitude

             console.log(userLatitude) // This prints the current latitude from the user
             console.log(userLongitude) // This prints the longitude



          },
          error => Alert.alert(error.message),
          { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 }
        );
      };


     //useEffect(()=>{
       // searchApi()
     //},[])



    return(


        <View style={styles.container}>
            <SearchBar 
                term={term}
                onTermChange={newTerm=>setTerm(newTerm)}
                onTermSubmit={()=> searchApi(term)}
                />
            <MapView
                style={styles.mapStyle}
                initialRegion={{
                latitude: 51.524300,
                longitude: -0.037790,
                latitudeDelta: 0.0122,
                longitudeDelta: 0.0421,
                }}
                >
                {parkingSpaces.map((val, index) => {
                return (<MapView.Marker
                        coordinate={{
                        latitude: parseInt(val.latitude),
                        longitude:parseInt(val.longitude)
                        }}
                        key={index}
                        title = {"parking markers"}
                        />); 

                })}

            </MapView>

            <Text>We have found {parkingSpaces.length} results</Text>
            <Button onPress={searchApi} title=" Click Here To Get Parking Spaces" />
            <Button onPress={findCoordinates} title=" Click Here To Get User's Location" />
            <Text> WC2A 3PD</Text>
            <Text>Parking Spaces found around {term}</Text>

            <FlatList
                data = {parkingSpaces}
                renderItem={({ item }) => {
                    return <MapView.Marker
                    coordinate={{
                    latitude: parseInt(item.latitude),
                    longitude:parseInt(item.longitude),
                    latitudeDelta:0.0,
                    longitudeDelta:0.0
                    }}

                    title = {"parking markers"}
                    description = {"parking"}


                    />  

                }}
                keyExtractor={item => item.unique_identifier}


            />

            <FlatList 
                data = {parkingSpaces}
                renderItem={({ item }) => {
                    return <Text> {item.road_name} | Possible Available Spaces:{item.parking_spaces} </Text>

                }}
            keyExtractor={item => item.unique_identifier}

            />


        </View>
    );
};

const styles = StyleSheet.create(
    {
     container:{
         flex:1,
         backgroundColor: '#fff',
         //alignItems: 'center',
         //justifyContent: 'center',
         //...StyleSheet.absoluteFillObject,
         //marginLeft:0,
         //height:400,
         //width:400,
         //justifyContent:"flex-end",
         //alignItems:"center",   
     },

     mapStyle: {
        width: 400,
        height:400, 
        //width: Dimensions.get('window').width,
        //height: Dimensions.get('window').height,
      },
    }

)

export default HomeScreen
import React,{Component,useState,useffect}来自'React'
从“react native”导入{视图、文本、样式表、维度、按钮、警报、平面列表}
从“react native maps”导入MapView,{Marker}
从“axios”导入axios
从“反应本机手势处理程序”导入{TextInput}
从“../api/camdenParking”导入camdenParking
从“../components/SearchBar”导入搜索栏
///关键机密:5ulg30lagu2o493uwsmn24rxklsg0ivb05k2zl6xqhiz8js9e7
///应用程序秘密令牌:NTEX14NQLBRS84RMC6RIUV6K2AQ_j687H
常量主屏幕=()=>
{
常量[ParkingSpace,SetParkingSpace]=useState([])
const[term,setTerm]=useState(“”)
让userLatitude=0
让userLongitude=0
const customData=require(“./MarkersText.json”)
const searchApi=async()=>{
const response=等待camdenParking.get(“”{
参数:{
//经度:-0.115444,
//纬度:51.517597
邮政编码:term
}
})//您可以稍后更改此选项
console.log(response.data)
设置停车空间(response.data)
console.log(术语)
}
常量findCoordinates=()=>{
navigator.geolocation.getCurrentPosition(
位置=>{
const locationString=JSON.stringify(position);//这里我们得到了JSON对象,但需要对其进行解析
var longLat=JSON.parse(locationString);//这里我们分析JSON对象
userLatitude=longLat.coords.latitude
userLongitude=longLat.coords.longitude
log(userLatitude)//这将从用户打印当前纬度
log(userLongitude)//这将打印经度
},
error=>Alert.Alert(error.message),
{enableHighAccurance:false,超时:20000,最大值:1000}
);
};
//useffect(()=>{
//
<MapView
 style={styles.mapStyle}
 initialRegion={{
 latitude: 51.524300,
 longitude: -0.037790,
 latitudeDelta: 0.0122,
 longitudeDelta: 0.0421,
}}
 >
 {parkingSpaces.map((val, index) => {
  return (<MapView.Marker
          coordinate={{
          latitude: val.latitude,
          longitude: val.longitude
          }}
          key={index}
          title = {"parking markers"}
         />); 
 })}

</MapView>