React native maps showsMyLocationButton position - android

I am using Expo react-native-app. I have some local data which I want show in maps. For maps I have used React-native-maps. I successfully pull the data and display in maps by using Marker. For user location I have used expo-location and expo-permission. That works fine. I have used React-native-maps one props called showsMyLocationButton, by default props boolean false. when I made it true I can able to see in IOS Emulator and i think by default position bottom-right. Android emulator I don't see the button at all. This is ios image and this android image. I want to display some data under the maps like a Bottom-Sheet, for that I have used this package. As a result it hide the ios' showsMyLocationButton.
I want to display the user current location Button like Uber. I tried lots of way to do that but could not able to achieve the goal. I want change the button icon as well but also failed. Really appreciate if someone Help me out.
I shared my code in Snack Ps. it only works in ios and Android, does not work in web View.
This is my code
import React, { useState, useEffect, useCallback } from 'react';
import {
Dimensions, StatusBar, StyleSheet, Text,
TextInput, TouchableOpacity, View, Button
} from 'react-native';
import Constants from 'expo-constants';
import Mapview, { Marker, Callout, PROVIDER_GOOGLE } from 'react-native-maps'
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';
import datas from './datas.json'
// You can import from local files
import Animated from 'react-native-reanimated';
import BottomSheet from 'reanimated-bottom-sheet';
// or any pure javascript modules available in npm
export default function App() {
const sheetRef = React.useRef(null);
const renderContent = () => (
<View
style={{
backgroundColor: 'white',
padding: 16,
height: 450,
}}
>
<Text>Swipe down to close</Text>
<Button
title="Open Bottom Sheet"
onPress={() => sheetRef.current.snapTo(0)}
/>
</View>
);
const [state, setstate] = useState({
"latitude": 60.1098678,
"longitude": 24.7385084,
"latitudeDelta": 1,
"longitudeDelta": 1
});
useEffect(() => {
_onMapReady();
}, [_onMapReady]);
const _onMapReady = useCallback(async () => {
const { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== `granted`) {
// console.log(`Permisson Denied`);
}
const location = await Location.getCurrentPositionAsync({ "accuracy": Location.Accuracy.High });
setstate({
...state,
"latitude": location.coords.latitude,
"longitude": location.coords.longitude
});
}, [state]);
return (
<View style={styles.container}>
<Mapview
provider={PROVIDER_GOOGLE}
initialRegion={state}
showsIndoors={true}
showsMyLocationButton={true}
zoomControlEnabled={true}
zoomEnabled={true}
zoomTapEnabled={true}
showsScale={true}
showsBuildings={true}
showsUserLocation={true}
showsCompass={true}
onMapReady={_onMapReady}
style={styles.mapStyle}>
{
datas.data?.map((i) => {
return (
<Marker
coordinate={{
"latitude": i.location.lat,
"longitude": i.location.lng
}}
animation={true}
key={i.id}
>
<Callout
style={{ "width": 100, "height": 50 }}>
<View>
<Text>{i.Property}</Text>
</View>
</Callout>
</Marker>
);
})
}
</Mapview>
<BottomSheet
ref={sheetRef}
snapPoints={[450, 300, 0]}
borderRadius={10}
renderContent={renderContent}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
"flex": 1,
"alignItems": `center`,
"justifyContent": `center`
// position: 'absolute',
},
mapStyle: {
"height": Dimensions.get(`window`).height,
"width": Dimensions.get(`window`).width
},
});

Related

Fetch data and add to variable

Hello I'm working with my project and I want to fetch poster_patch into variable to print every single image of miniatures in my app. Im working with react-native in. Here is some code of my app. I want to create function to fetch value of path_poster and add it after to uri
Top.js
`
import React,{useState,useEffect} from "react";
import { View, StyleSheet, Text } from "react-native";
import MovieBox from './MovieBox';
const API_URL="https://api.themoviedb.org/3/movie/top_rated?api_key=xxx"
export default function Top(){
const [movies,setMovies]=useState([]);
useEffect(()=>{
fetch(API_URL)
.then((res)=>res.json())
.then(data =>{
console.log(data);
setMovies(data.results);
})
}, [])
return (
movies.map((movieReq)=><MovieBox key ={movieReq.id} {...movieReq}/>)
);
};
`
MovieBox.js
`
import React from 'react';
import { View, StyleSheet, Text,Image } from "react-native";
const API_IMG = "https://image.tmdb.org/t/p/w500";
function MovieBox ({title, poster_patch,vote_average,release_date,overview}){
const styles = StyleSheet.create({
container: {
paddingTop: 50,
},
tinyLogo: {
width: 50,
height: 50,
},
logo: {
width: 66,
height: 58,
},
});
return(
<View>
<Text>
{title} rated:
{vote_average}
</Text>
<Image source={{
uri: API_IMG + HERE I WANT TO ADD VARIABLE TO POSTER_PATCH,
}}
style={styles.tinyLogo}
/>
</View>
)
}
export default MovieBox;
`
How to get values from poster_path and add it into uri
Join base url and path for example using concat.
<Image source={{
uri: API_IMG.concat(poster_path),
}}
style={styles.tinyLogo}
/>
See Images for details.

Share image on whatsapp from react native android app

I am currently working on react-native photo sharing app for Android. Used native share method but it only share message and title. No options to share an image.
Looking after so many questions here couldn't find any straight forward way.
Please provide help.
This is the message I am getting Share awesome status on whatsapp using Khela #imageurl. Download #urltoplaystore
To share any image in React Native you are right you need to use the Share from react-native library itself, and you were wondering what is needed for an image, the answer it's really simple, you just need to use a Base64 image.
Check it out a working snack: snack.expo.io/#abrahamcalf/share-image
Wrap the code:
import * as React from 'react';
import {
Text,
View,
StyleSheet,
Image,
Share,
TouchableOpacity,
} from 'react-native';
export default class App extends React.Component {
state = {
cat: 'data:image/jpeg;base64,some-encoded-stuff;
};
handleSharePress = () => {
Share.share({
title: 'Share',
message: 'My amazing cat 😻',
url: this.state.cat,
});
};
render() {
return (
<View style={styles.container}>
<Image source={{ uri: this.state.cat }} style={styles.img} />
<TouchableOpacity onPress={this.handleSharePress}>
<Text>Share Image</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'space-around',
alignItems: 'center',
},
img: {
width: 200,
height: 300,
},
});
If you want to try something else, probably complex, I recommend to check out the react-native-share library from the React Native Community.
import Icon from 'react-native-vector-icons/Feather';
import Share from 'react-native-share';
import RNFetchBlob from 'rn-fetch-blob';
import React, {Component} from 'react';
const fs = RNFetchBlob.fs;
class ProductDetail extends Component {
constructor(props) {
super(props);
this.state = {};
}
shareTheProductDetails(imagesPath) {
let {productDetails} = this.state;
let imagePath = null;
RNFetchBlob.config({
fileCache: true,
})
.fetch('GET', imagesPath.image)
// the image is now dowloaded to device's storage
.then((resp) => {
// the image path you can use it directly with Image component
imagePath = resp.path();
return resp.readFile('base64');
})
.then((base64Data) => {
// here's base64 encoded image
var imageUrl = 'data:image/png;base64,' + base64Data;
let shareImage = {
title: productDetails.product_name, //string
message:
'Description ' +
productDetails.product_description +
' http://beparr.com/', //string
url: imageUrl,
// urls: [imageUrl, imageUrl], // eg.'http://img.gemejo.com/product/8c/099/cf53b3a6008136ef0882197d5f5.jpg',
};
Share.open(shareImage)
.then((res) => {
console.log(res);
})
.catch((err) => {
err && console.log(err);
});
// remove the file from storage
return fs.unlink(imagePath);
});
}
render() {
return (
<TouchableOpacity
style={{
borderWidth: 0,
left:(5),
top:(2),
}}
onPress={() =>
this.shareTheProductDetails(images)
}>
<Icon
style={{
left: moderateScale(10),
}}
name="share-2"
color={colors.colorBlack}
size={(20)}
/>
</TouchableOpacity>
)}
}

Unable to render flat list while searching

I have a list view in which list item component is designed by me.
If I render listItem alone it is working fine but after integrating ith with SearchBar I am not able to render them even though am able to get object matching a particular search
SearchListItem
import React from 'react';
import {Image, Text, View} from "react-native";
export default class SearchListItem extends React.Component
{
render()
{
return (
<View style={{flexDirection: 'row'}}>
<Image source={{uri: this.props.src}}
style={{width: 50, height: 50, backgroundColor: '#fff'}} />
<Text style={{height: 50, lineHeight: 50, width: '100%',textAlign: 'center', flex:1, backgroundColor: '#FFF'}}>{this.props.text}</Text>
</View>
)
}
}
App.js
import React from 'react';
import {FlatList, StyleSheet, Text, TextInput, View} from 'react-native';
import SearchListItem from "./components/SearchListItem";
import { SearchBar } from 'react-native-elements';
import { includes } from 'lodash';
export default class App extends React.Component {
constructor(props)
{
super(props);
this.all_categories = [
{
"id": "1",
"text": "abc",
"src": "https://cdn-images-1.medium.com/max/1200/1*dIocy2HvI_BIpziOypf8ig.jpeg"
},
{
"id": "2",
"text": "dbef",
"src": "https://cdn-images-1.medium.com/max/1200/1*dIocy2HvI_BIpziOypf8ig.jpeg"
},
{
"id": "3",
"text":"bghi",
"src":"https://cdn-images-1.medium.com/max/1200/1*dIocy2HvI_BIpziOypf8ig.jpeg"
},
{
"id": "4",
"text":"jbkl",
"src":"https://cdn-images-1.medium.com/max/1200/1*dIocy2HvI_BIpziOypf8ig.jpeg"
}
];
this.state = {text:"",
categories: []
}
}
search(text)
{
var searchResults = [];
var categories = this.all_categories;
for (var i = categories.length - 1; i >= 0; i--)
{
includes(categories[i]['text'], text) && searchResults.push(categories[i])
}
console.log("text searched is " + text);
console.log(searchResults);
return searchResults;
}
_keyExtractor = (item, index) => item.id;
_renderItem(item)
{
console.log("item to render is");
console.log(item);
return <SearchListItem text={item.text} src={item.src}/>
}
render() {
console.log("rendered");
console.log("categories to display are");
console.log(this.state.categories);
return (
<View>
<View style={{height:30,width:"100%"}}/>
<SearchBar
round
lightTheme
containerStyle={{
backgroundColor:'transparent',
borderTopWidth: 0,
borderBottomWidth: 0,
}}
placeholder="Search!"
inputStyle = {{backgroundColor:'white'}}
onChangeText={ (text) =>
{
let result = this.search(text);
console.log("changing state");
this.setState({categories:result, text:text})
}}
value={this.state.text}
/>
<FlatList style={{flex:1}}
removeClippedSubviews={false}
data={this.state.categories}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
/>
</View>
)
}
}
Searching gives all the valid results but not able to show the list corresponding to the results.What I have done wrong?
Running your code I found two little mistakes:
First one is in _renderItem param, which has to be like
_renderItem({item})
{
console.log("item to render is");
console.log(item);
return <SearchListItem text={item.text} src={item.src}/>
}
as destructuring suggest (see doc).
Second one causes your list not rendering:
try remove that style={{flex:1}} in FlatList props.
I've just created a snack if you want to check it:

React navigation header title cut off

So basically i'm in the process of learning react native. I'm using the react navigation package and I just want to display a simple header title on my stack navigator but the title cuts off. Stack nav title
This is my App.js
import React from 'react';
import { View, Text } from 'react-native';
import { createStackNavigator, createAppContainer} from 'react-navigation'
import HomeScreen from './screens/HomeScreen'
import DetailsScreen from './screens/DetailsScreen'
const RootStack = createStackNavigator(
{
Home: HomeScreen,
Details: DetailsScreen,
},
{
initialRouteName: 'Home'
}
);
const AppContainer = createAppContainer(RootStack)
export default class App extends React.Component {
render(){
return<AppContainer />
}
}
and this is my HomeScreen.js
import React from 'react'
import {Button, View, Text } from 'react-native'
export default class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Home',
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screeeen</Text>
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('Details')}
/>
</View>
)
}
}
It doesnt look like this on my friends phones. I'm using a OnePlus 6 with android 9. They are on older versions of android could that be causing something?
Turns out this is a specific problem affecting OnePlus user who has chosen to use the font OnePlus Slate instead of for exmaple robot. Changing the font in the phone fixes the problem, alternatively you force the usage of a font in the app and it should work as well
I got the same problem running on a OnePlus phone and solved it without the font loader but style with the navigation option in headerTitleStyle width like so:
import { Dimensions } from 'react-native';
const WIDTH = Dimensions.get('window').width;
export const MyStackNav = createStackNavigator(
{
Tab1: {
screen: Tab1,
navigationOptions: ({ navigation }) => ({
headerTitle: `${navigation.state.routeName} page`,
headerTitleStyle: {
width: WIDTH - 75,
},
}),
},
...more code
}
A similar issue also occurs in various components like button in one plus devices. One way to solve it by giving some minimum width to the label style, so that you don't have to switch the font family, helps if you are using some custom fonts
Solution: width: '100%' or some fixed value like minWidth: 100
Code example in drawer navigation
<DrawerItem
labelStyle={{ minWidth: 100 }}
label={`Orders`}
onPress={() => {}}
/>

How to call function in another component from Drawer in React Native

We have the following code within I have the method createDrawerNavigator in my App.js file
const RootDrawer = createDrawerNavigator({
Home: { screen: HomeScreen },
Detail: { screen: DetailScreen },
Result: { screen: ResultScreen },
Section : { screen: SectionScreen }
},{
contentComponent : ({ navigation }) => (<SideBar navigation={navigation} />),
initialRouteName: 'Home',
navigationOptions: {
headerStyle: {
backgroundColor: '#26272d',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
},
transitionConfig: () => ({
transitionSpec: {
duration: 500,
easing: Easing.out(Easing.poly(4)),
timing: Animated.timing,
},
screenInterpolator: sceneProps => {
const { layout, position, scene } = sceneProps;
const { index } = scene;
const height = layout.initHeight;
const translateY = position.interpolate({
inputRange: [index - 1, index, index + 1],
outputRange: [height, 0, 0],
});
const opacity = position.interpolate({
inputRange: [index - 1, index - 0.99, index],
outputRange: [0, 1, 1],
});
return { opacity, transform: [{ translateY }] };
},
}),
});
And I have the screen SideBar that acts as Drawer:
import React, { Component, PureComponent } from 'react';
import { connect } from 'react-redux';
import { Image, StyleSheet, View, TouchableOpacity, Text, Linking } from 'react-native';
import { Icon } from 'native-base';
import {StackActions, NavigationActions, DrawerActions} from 'react-navigation';
import Ionicons from 'react-native-vector-icons/Ionicons';
export default class SideBar extends React.Component {
goTo = (section) => {
const resetAction = StackActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'Section' })
]
})
return () => this.props.navigation.dispatch(resetAction);
}
render() {
return(
<View style={styles.container}>
<View>
<View style={styles.logo}><Image source={require('./images/ln-header-bg.jpg')} style={styles.ln_logo} resizeMode="contain" /></View>
<TouchableOpacity style={styles.link_menu} onPress={() => { this.goTo('all'); }}><Text style={styles.link_menu_text}>Últimas noticias</Text></TouchableOpacity>
<TouchableOpacity style={styles.link_menu} onPress={() => { this.goTo(68); }}><Text style={styles.link_menu_text}>La Nación</Text></TouchableOpacity>
<TouchableOpacity style={styles.link_menu} onPress={() => { this.goTo(69); }}><Text style={styles.link_menu_text}>El Mundo</Text></TouchableOpacity>
<TouchableOpacity style={styles.link_menu} onPress={() => { this.goTo(70); }}><Text style={styles.link_menu_text}>Gente</Text></TouchableOpacity>
<TouchableOpacity style={styles.link_menu} onPress={() => { this.goTo(97); }}><Text style={styles.link_menu_text}>#YoParticipo</Text></TouchableOpacity>
</View>
<View>
<Text style={styles.follow_social}>Síguenos en las redes</Text>
<View style={styles.follow_social_links}>
</View>
</View>
</View>
)
}
}
In the SideBar I want to call an function located in Home Component, I tried with react navigation dispacth method but doesn't working.
What I have to call the function or navigate to another screen? Can some help me please?
Thanks!
I never used drawers from react-navigation, but I would assume that the way they work is similar to stackNavigators. So, assuming that, what you could do was to set a navigation parameter in the Home screen, for example, inside the componentDidMount() method, like so:
this.props.navigation.setParams({ 'paramName': paramValue });
and then, in the drawer, in the componentWillMount() method, you could do something like:
const var_x = this.props.navigation.getParam('paramName', null);
This way, you can either send the function itself as a parameter, or send a reference to the Home screen, and then access its methods from the drawer.
ps: on both calls, paramName needs to be a string.
ps2: in the getParam method call, the second argument, in the example, null, is the default value in case there is not a value for the requested parameter.
Again, I use this method for stackNavigators, so you might take a look at the react-navigation documentation to double check if there is any difference for drawer: https://reactnavigation.org/docs/en/drawer-navigator.html#docsNav

Categories

Resources