StorePosition.js 12.5 KB
import React,{ Component } from 'react'

import {View,Text,RefreshControl,Image,ScrollView,Dimensions,TextInput,TouchableOpacity,StatusBar,StyleSheet} from 'react-native'
import { post, get, put, delete as remove } from 'axios'

import * as Location from 'expo-location';
import {AsyncStorage} from 'react-native'
import { Icon } from 'native-base'; // 추가된 코드
import MapView, { Marker, Polyline, LocalTile } from "react-native-maps";
import Custom_Marker from '../../assets/marker.svg'
import MapApi from "react-native-daummap";

import RNKakaoLink from 'react-native-kakao-links';
import { SERVER } from '../../common/servername';
import { getDistance, getPreciseDistance } from 'geolib';

const linkObject={
    webURL                :'https://developers.kakao.com/docs/android/kakaotalk-link',//optional
    mobileWebURL          :'https://developers.kakao.com/docs/android/kakaotalk-link',//optional
    androidExecutionParams:'shopId=1&itemId=24', //optional For Linking URL
    iosExecutionParams    :'shopId=1&itemId=24', //optional For Linking URL
};

const contentObject = {
    title     : '제목',
    link      : linkObject,
    imageURL  : 'https://mud-kage.kakao.co.kr/dn/NTmhS/btqfEUdFAUf/FjKzkZsnoeE4o19klTOVI1/openlink_640x640s.jpg',
  
    desc      : '설명',//optional
    imageWidth: 240,//optional
    imageHeight:240//optional
  }
  
  //5개의 속성 중 최대 3개만 표시해 줍니다. 우선순위는 Like > Comment > Shared > View > Subscriber 입니다.
  const socialObject ={
    likeCount:12,//optional
    commentCount:1,//optional
    sharedCount:23,//optional
    viewCount:10,//optional
    subscriberCount:22//optional
  }
  
  const buttonObject = {
    title:'앱으로보기',//required
    link : linkObject,//required
  }
  
  
  const commerceDetailObject ={
    regularPrice :10000,//required,
    // discountPrice:1000,//Optional
    // discountRate:10,//Optional
    // fixedDiscountPrice:1000//Optional
  };
  
  
class MainPage extends Component {

    state = {
        refreshing:false,
    }

    constructor(props) {
        super(props)
        this.state= {
            location:null,
            errorMsg:null,
            current:"",
            coordinate:[],
            item:{},
            fires:[],
            state:false,
        }
    }
    _getDistance = () => {
        var dis = getDistance(
          { latitude: 20.0504188, longitude: 64.4139099 },
          { latitude: 51.528308, longitude: -0.3817765 }
        );
        alert(`Distance\n${dis} Meter\nor\n${dis / 1000} KM`);
      };
    
      _getPreciseDistance = () => {
        var pdis = getPreciseDistance(
          { latitude: 20.0504188, longitude: 64.4139099 },
          { latitude: 51.528308, longitude: -0.3817765 }
        );
        alert(`Precise Distance\n${pdis} Meter\nor\n${pdis / 1000} KM`);
      };
    
  linkCustom = async () => {
    try{
        const options = {
          objectType:'feed',//required
          content:contentObject,//required
          social:socialObject,//optional
          buttons:[buttonObject]//optional
        };
        const response = await RNKakaoLink.link(options);
  
      }catch(e){
        console.warn(e);
      }
  }
    componentDidMount() {
        (async () => {
            AsyncStorage.getItem("user",(err,res) => {
                if(res) {
                    this.setState({
                        user:JSON.parse(res)
                    })

                }
            })
            if(!this.props.navigation.state.params) {
                alert("잘못된 접근입니다.")
                return this.props.navigation.goBack(null)}
            get(`http://${SERVER}/fire`).then(res => {
                this.setState({
                    fires:res.data.data
                })
            }).catch(e => console.log(e))
            get(`http://${SERVER}/stores/${this.props.navigation.state.params.item.id}`).then((res)  => {
                this.setState({
                    item:res.data.data[0]
                },async () => {
                    let location = await Location.getCurrentPositionAsync({});
            
                    this.setState({
                        location
                    },() => {
                        MapApi.getCoordToAddress(location.coords.latitude,location.coords.longitude).then(res => {
                            this.setState({
                                current:res.documents[0].road_address.address_name
                            })
                        })
                    })  
                })
            })
    })();
        
    }
    handleNavigate = () => {
    get(`https://naveropenapi.apigw.ntruss.com/map-direction/v1/driving?start=${this.state.location.coords.longitude},${this.state.location.coords.latitude}goal=${parseFloat(this.state.item.longitude)},${parseFloat(this.state.item.latitude)}&option=traoptimal`
    ,{headers:{'X-NCP-APIGW-API-KEY-ID':'4wo5mih29n','X-NCP-APIGW-API-KEY':'LAFshg9A5XyGTSUXWwJYiP6zX5gK7VQUr4vrUc6r'}}).then(res => {
        console.log(res.data)
        if(res.data && res.data.route) {
            console.log(res.data.route)
        res.data.route.traoptimal[0].path.map((e,i) => {
            console.log(e)
            this.setState((prev) => ({
                coordinate: [
                    ...prev.coordinate,
                    {longitude:e[0],latitude:e[1]}
                ]
            }))
        })
        }
    })
        

    }
    Cal_Distance = () => {
        if( this.state.fires.filter((e,i) => {
            if(getDistance(
                { latitude: this.state.location.coords.latitude, longitude: this.state.location.coords.longitude },
                { latitude: e.latitude, longitude: e.longitude })<500) {
                    return true
            }
        }).length > 0 && !this.state.state) {
            this.setState({
                state:true
            })
            post(`http://${SERVER}/fire_catch`,{id:this.state.user.id}).then(res => {
                if(!res.data.success) {
                    this.setState({
                        state:false
                    })
                }
            })
        }
        

    }
    render() {

        return (
            <View style={{height:"100%",width:"100%",backgroundColor:"transparent"}}>
            <View style={{display:"flex",flexDirection:"row", height:"8%",backgroundColor:"#5f6161",alignItems:"center"}}>
                <Icon name="ios-arrow-back" style={{color:"#f4cd37", paddingLeft:10}}/>
                <Text style={{fontSize:17,color:"white",paddingLeft:10}}>위치</Text>
            </View>
                {this.state.location?<MapView 
                initialRegion={{ 
                    latitude: this.state.location.coords.latitude, 
                    longitude: this.state.location.coords.longitude, 
                    latitudeDelta: 0.005, 
                    longitudeDelta: 0.001, 
                }}
                maxZoom= {20}
                minZoom= {1}
                onRegionChange={this.Cal_Distance}
                onUserLocationChange={() => this.Cal_Distance()}
                 style={{width:"100%",height:"84%"}} >
                 {this.state.coordinate.map((e,i) => {
                     return <Polyline
                     key={i}
                     coordinates={this.state.coordinate}
                     strokeColor="#FFD63A" // fallback for when `strokeColors` is not supported by the map-provider
                     strokeWidth={5} />
                 })}
                 {this.state.fires.map((e,i) => {
                     return (
                         <MapView.Circle
                         center={{
                             latitude:parseFloat( e.latitude),
                             longitude:parseFloat( e.longitude),
                         }}
                         radius={40}
                         fillColor={"rgba(204,117,63,0.5)"}
                         >
                                 <Text style={{textAlign:"center",color:"white",fontSize:9,fontWeight:"bold"}}>
                                    주의!
                                </Text>
                         </MapView.Circle>
                     )
                 })}
                 <Marker 
                    coordinate={{
                    latitude: this.state.location.coords.latitude, 
                    longitude: this.state.location.coords.longitude}} 
                    title="내 위치"
                    description={`${this.state.current}`}>
                        <Custom_Marker/>
                        <MapView.Callout  style={{alignItems:"center",width:260}}>
                            <View style={{width:"100%"}}>
                                <Text style={{fontWeight:"bold"}}>
                                     위치
                                </Text>    
                                <Text>
                                    {`${this.state.current}`}
                                </Text>    
                            </View>    
                        </MapView.Callout>
                    </Marker>

                    
                 <Marker 
                    coordinate={{
                    latitude: this.state.item.latitude , 
                    longitude:this.state.item.longitude}} 
                    title="내 위치"
                    description={`${this.state.current}`}>
                        <Custom_Marker/>
                        <MapView.Callout tooltip={true} style={{backgroundColor:"transparent",width:260,flexDirection:"row",paddingLeft:0}}>
                            <Text style={{lineHeight:25,}}>
                                <Image resizeMode="stretch" style={{width:78,height:50,marginTop:0,paddingTop:0,paddingLeft:0,marginLeft:0}} source={require('../../assets/img.png')}/>
                            </Text >
                            <View style={{borderWidth:2,borderColor:"#FFD63A",width:182,backgroundColor:"white",borderLeftWidth:0}}>
                            <View style={{marginLeft:8,justifyContent:"center",fontSize:13,color:"black"}}>
                                <Text>
                                    {this.state.item.name}
                                </Text>    
                                <Text style={{color:"#808083",fontSize:12}}>
                                    {this.state.item.phone_number}
                                </Text>    
                            </View>    
                            </View>
                        </MapView.Callout>
                    </Marker>
                 </MapView>:<MapView></MapView>}

            <View style={{flexDirection:"row",width:"100%",height:"8%",position:"absolute",justifyContent:"center",bottom:0,alignItems:"center"}}>     
                <TouchableOpacity onPress={() => {this.handleNavigate()}} style={{width:"50%",height:"100%",justifyContent:"center",backgroundColor:"#f4cd37"}}>
                    <Text style={{fontSize:17,color:"black",paddingLeft:10,textAlign:"center"}}>길찾기</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => {this.linkCustom()}} style={{width:"50%",height:"100%",justifyContent:"center",backgroundColor:"white"}}>
                    <Text style={{fontSize:17,color:"black",paddingLeft:10,textAlign:"center"}}>공유하기</Text>
                </TouchableOpacity>
            </View>
            </View>
        )

    }

}

const style=StyleSheet.create({
    list_pick_event: {
        paddingTop:17,
        paddingBottom:17,
        borderBottomColor:"#BBB9B9",
        borderTopColor:"#BBB9B9",
        borderBottomWidth:0.5,
    },
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    avatar : {
        width:32,
        height:32,
        borderRadius:100,
    },
    detail: {
        marginLeft:15,
        flex:1,
        flexDirection:"row",
    },
    hit: {
        fontSize:9,
        fontWeight:"bold"
    },
    date: {
        marginLeft:9,
        fontSize:9,
        color:"black"
    },
    userWrapper : {
        flex:1,
        flexDirection:"row",
        paddingTop:13,
        paddingBottom:17,
        borderBottomColor:"#AEAEAE",
        borderBottomWidth:1,
    },
    nickname : {
        marginLeft:10,
        fontSize:13,
        fontWeight:"bold",
        color:"black"
    },
    title : {
        fontSize:13,
        fontWeight:"bold",
        color:"black"
    },
    like : {
        marginTop:3,
        fontSize:10,
        color:"red",
        marginLeft:5,
    },
    titleWrapper : {
        marginTop:17,
        paddingLeft:19,
        flex:1,
        flexDirection:"row"
    }
})
export default MainPage