How to get the address from google maps autocomplete in React Native - google-maps

I am using react-native-google-places-autocomplete to select a location. I want to extract the location selected and use it in other component.
How can I save the address
This is my code
import React, {Component} from 'react';
import { View, Image, Text, StyleSheet } from 'react-native';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
const homePlace = { description: 'Home', geometry: { location: { lat: 48.8152937, lng: 2.4597668 } }};
const workPlace = { description: 'Work', geometry: { location: { lat: 48.8496818, lng: 2.2940881 } }};
export default class google extends Component {
render(){
return (
<View style={styles.container}>
<View style={styles.top}>
<GooglePlacesAutocomplete
placeholder='Search'
minLength={2} // minimum length of text to search
autoFocus={false}
returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
listViewDisplayed='auto' // true/false/undefined
fetchDetails={true}
renderDescription={row => row.description} // custom description render
onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
console.log(data, details);
this.setState(
{
address: data.description, // selected address
coordinates: `${details.geometry.location.lat},${details.geometry.location.lng}` // selected coordinates
}
);
}}
getDefaultValue={() => ''}
query={{
// available options: https://developers.google.com/places/web-service/autocomplete
key: 'AIzaS#################',
language: 'es', // language of the results
}}
styles={{
textInputContainer: {
width: '100%'
},
description: {
fontWeight: 'bold'
},
predefinedPlacesDescription: {
color: '#1faadb'
}
}}
currentLocation={true} // Will add a 'Current location' button at the top of the predefined places list
currentLocationLabel="Current location"
nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
GoogleReverseGeocodingQuery={{
// available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
}}
GooglePlacesSearchQuery={{
// available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
rankby: 'distance',
types: 'food'
}}
filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities
predefinedPlaces={[homePlace, workPlace]}
debounce={200} // debounce the requests in ms. Set to 0 to remove debounce. By default 0ms.
renderRightButton={() => <Text>Custom text after the input</Text>}
/>
</View>
<View style={styles.container2}>
<Text>
hola {this.setState.address}
</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
width: '100%',
height: '100%',
},
welcome: {
fontSize: 40,
textAlign: 'center',
margin: 10,
color:'black',
},
instructions: {
textAlign: 'center',
color: 'black',
marginBottom: 5,
},
top: {
height: '50%',
justifyContent: 'center',
alignItems: 'center',
},
container2: {
height:'75%',
justifyContent: 'center',
},
buttonContainer: {
alignItems: 'center',
backgroundColor: 'rgba(255, 255,255, 0.5)',
padding: 1,
margin: 50,
borderRadius: 25,
borderWidth: 2,
borderColor: '#0B0B3B'
},
textoboton: {
textAlign: 'center',
color: 'black',
marginBottom: 5,
fontSize: 12
},
})
I've been also using another library with some differences
app.js
import React,{Component} from 'react';
import { Constants } from 'expo';
import Icon from 'react-native-vector-icons/FontAwesome';
import { View, Image, Text, StyleSheet, AsyncStorage, Button,ScrollView, TextInput, ActivityIndicator } from 'react-native';
import {
NavigationActions
} from 'react-navigation';
import { GoogleAutoComplete } from 'react-native-google-autocomplete';
import {Card, Input} from "react-native-elements";
import LocationItem from './locationItem';
export default class App extends React.Component {
state={
datos:[],
}
componentDidMount(){
this._loadedinitialstate().done();
}
_loadedinitialstate =async() => {
AsyncStorage.getItem('datos');
}
render() {
return (
<View style={styles.container}>
<GoogleAutoComplete apiKey={'AIzaSyB2HyNTBm1sQJYJkwOOUA1LXRHAKh4gmjU'} debounce={20} minLength={2} getDefaultValue={() => ''} onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
console.log(data, details);}} returnKeyType={'default'} fetchDetails={true}
>
{({
locationResults,
isSearching,
clearSearchs,
datos,
handleTextChange
}) => (
<React.Fragment>
<View style={styles.inputWrapper}>
<Input
style={styles.textInput}
placeholder="Ingresa tu direccion"
onChangeText={(datos) => this.setState({datos})}
value={datos}
/>
</View>
{isSearching && <ActivityIndicator size="large" color="red" />}
<ScrollView>
{locationResults.map(el => (
<LocationItem
{...el}
key={el.id}
/>
))}
</ScrollView>
</React.Fragment>
)}
</GoogleAutoComplete>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
textInput: {
height: 40,
width: 300,
borderWidth: 1,
paddingHorizontal: 16,
},
inputWrapper: {
marginTop: 80,
flexDirection: 'row'
},
});
locationitem.js
import React, { PureComponent } from 'react';
import { View, Alert, Text, StyleSheet, TouchableOpacity, AsyncStorage} from 'react-native';
class LocationItem extends PureComponent {
constructor(props) {
super(props);
this.state = {datos:''};
}
_handlePress = () => {
AsyncStorage.setItem('datos',datos)
}
render() {
return (
<TouchableOpacity style={styles.root} onPress={this._handlePress} >
<Text value={this.state.datos}> {this.props.description} </Text>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
root: {
height: 40,
borderBottomWidth: StyleSheet.hairlineWidth,
justifyContent: 'center'
}
})
export default LocationItem;
The source of both codes is here react-native-google-places-autocomplete enter link description here
Which code will be easy to use, and How can I solve my Issue (get the address) ??
Any Answer will be Helpful

first install
npm i react-native-google-places-autocomplete
then
import React from 'react';
import { View, Image } from 'react-native';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
const homePlace = { description: 'Home', geometry: { location: { lat: 48.8152937, lng: 2.4597668 } }};
const workPlace = { description: 'Work', geometry: { location: { lat: 48.8496818, lng: 2.2940881 } }};
const GooglePlacesInput = () => {
return (
<GooglePlacesAutocomplete
placeholder='Search'
minLength={2} // minimum length of text to search
autoFocus={false}
returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
listViewDisplayed='auto' // true/false/undefined
fetchDetails={true}
renderDescription={row => row.description} // custom description render
onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
console.log(data, details);
}}
getDefaultValue={() => ''}
query={{
// available options: https://developers.google.com/places/web-service/autocomplete
key: 'YOUR API KEY',
language: 'en', // language of the results
types: '(cities)' // default: 'geocode'
}}
styles={{
textInputContainer: {
width: '100%'
},
description: {
fontWeight: 'bold'
},
predefinedPlacesDescription: {
color: '#1faadb'
}
}}
currentLocation={true} // Will add a 'Current location' button at the top of the predefined places list
currentLocationLabel="Current location"
nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
GoogleReverseGeocodingQuery={{
// available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
}}
GooglePlacesSearchQuery={{
// available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
rankby: 'distance',
types: 'food'
}}
filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities
predefinedPlaces={[homePlace, workPlace]}
debounce={200} // debounce the requests in ms. Set to 0 to remove debounce. By default 0ms.
renderLeftButton={() => <Image source={require('path/custom/left-icon')} />}
renderRightButton={() => <Text>Custom text after the input</Text>}
/>
);
}

After a long journey, these steps helped me solve the problem.
1) Install npm install react-native-google-places-autocomplete --save.
2) Then use this code below, as an element in your component.
<GooglePlacesAutocomplete
query={{
key: "GOOGLE_PLACES_API_KEY",
language: "en", // language of the results
}}
onPress={(data, details = null) => {
console.log(details);
console.log(data);
console.log("data.description",data.description.split(','));
}}
onFail={(error) => console.error(error)}
listViewDisplayed="false"
requestUrl={{
url:
"https://cors-
anywhere.herokuapp.com/https://maps.googleapis.com/maps/api",
useOnPlatform: "web",
}} // this in only required for use on the web. See https://git.io/JflFv
more for details.
styles={{
textInputContainer: {
backgroundColor: "rgba(0,0,0,0)",
borderTopWidth: 0,
borderBottomWidth: 0,
},
textInput: {
marginLeft: 0,
marginRight: 0,
height: 38,
color: "#5d5d5d",
fontSize: 16,
},
predefinedPlacesDescription: {
color: "#1faadb",
},
}}
/>
3) You may have the same problem that i had, which the list disappears when i try to select result. However, this is the action that solved this problem for me.
Commenting out onBlur on node_modules. path: "..\node_modules\react-native-google-places-autocomplete\GooglePlacesAutocomplete.js".
...
onFocus={onFocus ? () => {this._onFocus(); onFocus()} : this._onFocus}
// onBlur={this._onBlur}
underlineColorAndroid={this.props.underlineColorAndroid}
...
4) For saving the address you can check the console.log in the code, and then use setState or something like this.
5) For more information and options of these element check out this repository:
https://github.com/FaridSafi/react-native-google-places-autocomplete.
hope this will help for you :)

First of all, I used listViewDisplayed={false} because otherwise the list view get stuck with the results, and even on location press the list doesn't closes.
Second, to answer your question: The results are in the onPress function of GooglePlacesAutocomplete, you can update the state with the chosen location and then use it where ever you want in your component:
onPress={(data, details = null) => {
this.setState({
latitude: details.geometry.location.lat,
longitude: details.geometry.location.lng,
moveToUserLocation: true
});
this._gotoLocation();
}
}
As i wrote it, onPress also trigger the function that moves the map to display the new location.

import React, {Component} from 'react';
import { View, Image, Text, StyleSheet } from 'react-native';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
export default class google extends Component {
constructor(props) {
super(props);
this.state = {
address:null,
lat:null,
lng:null,
}
}
getAdd(data){
console.log("add",data);
this.setState(
{
address: data.formatted_address, // selected address
lat: data.geometry.location.lat,// selected coordinates latitude
lng:data.geometry.location.lng, // selected coordinates longitute
}
);
console.log("this.state.address",this.state.address); ///to console address
console.log("this.state.coordinates",this.state.lat,this.state.lng); /// to console coordinates
}
render(){
return (
<View style={styles.container}>
<View style={styles.top}>
<GooglePlacesAutocomplete
placeholder='Search'
minLength={2} // minimum length of text to search
autoFocus={false}
fetchDetails={true}
returnKeyType={'default'}
onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
var data = details;
this.getAdd(data);
}}
query={{
// available options: https://developers.google.com/places/web-service/autocomplete
key: 'AIzaS#################',
language: 'en',
types: 'geocode', // default: 'geocode'
}}
listViewDisplayed={this.state.showPlacesList}
textInputProps={{
onFocus: () => this.setState({ showPlacesList: true }),
onBlur: () => this.setState({ showPlacesList: false }),
}}
styles={{
textInputContainer: {
width: '100%'
},
description: {
fontWeight: 'bold'
},
predefinedPlacesDescription: {
color: '#1faadb'
}
}}
currentLocation={true} // Will add a 'Current location' button at the top of the predefined places list
currentLocationLabel="Current location"
nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities
// predefinedPlaces={[]}
predefinedPlacesAlwaysVisible={true}
/>
</View>
{ this.state.address !=null ?(
<View style={styles.container2}>
<Text>
Address: {this.state.address}
</Text>
</View>
):null }
</View>
);
}
}
const styles = StyleSheet.create({
container: {
width: '100%',
height: '100%',
},
welcome: {
fontSize: 40,
textAlign: 'center',
margin: 10,
color:'black',
},
instructions: {
textAlign: 'center',
color: 'black',
marginBottom: 5,
},
top: {
height: '50%',
justifyContent: 'center',
alignItems: 'center',
},
container2: {
height:'75%',
justifyContent: 'center',
},
buttonContainer: {
alignItems: 'center',
backgroundColor: 'rgba(255, 255,255, 0.5)',
padding: 1,
margin: 50,
borderRadius: 25,
borderWidth: 2,
borderColor: '#0B0B3B'
},
textoboton: {
textAlign: 'center',
color: 'black',
marginBottom: 5,
fontSize: 12
},
})

Related

"temporary" variant not showing in Drawer component Material-ui

I am trying to make the drawer component on material-ui a responsive drawer, by making it to be toggled open and close on smaller screens and permanent on desktop
I followed the documentation on mui, which says to add the temporary variant to the drawer, however it doesn't show up at all on desktop mode
Below is my drawer component
import React from "react";
import ReactDOM from "react-dom";
import { useHistory } from "react-router-dom";
import { makeStyles, Typography, Drawer, Toolbar, Divider, List, ListItem, ListItemText, ListItemIcon, Container, Box } from "#material-ui/core";
import HomeOutlinedIcon from '#material-ui/icons/HomeOutlined';
import AlternateEmailOutlinedIcon from '#material-ui/icons/AlternateEmailOutlined';
import NotificationsNoneOutlinedIcon from '#material-ui/icons/NotificationsNoneOutlined';
import DashboardOutlinedIcon from '#material-ui/icons/DashboardOutlined';
import ArchiveOutlinedIcon from '#material-ui/icons/ArchiveOutlined';
const drawerWidth = 280
const useStyles = makeStyles((theme) => ({
drawer : {
width: drawerWidth,
},
drawerPaper : {
width: drawerWidth,
},
list : {
marginLeft: '24px',
marginRight: '24px'
},
listItem : {
padding: '8px',
borderRadius: '5px',
},
text : {
color: theme.palette.primary.light,
fontWeight: '500',
lineHeight: '2000'
},
title : {
color: theme.palette.primary.light,
textAlign: 'center',
display: 'block',
fontWeight: '500',
fontSize: '20px',
marginTop: '10px',
marginBottom: '10px'
}
}));
export default function LeftBar(){
const classes = useStyles();
const [mobileOpen, setMobileOpen] = React.useState(false);
const handleDrawerToggle = () => {
setMobileOpen(!mobileOpen);
};
const list = [
{
text : 'Home',
icon : <HomeOutlinedIcon />,
path : '/'
},
{
text : 'Personal',
icon : <AlternateEmailOutlinedIcon />,
path : '/'
},
{
text : 'Notificatons',
icon : <NotificationsNoneOutlinedIcon />,
path : '/'
},
{
text : 'Dashboard',
icon : <DashboardOutlinedIcon />,
path : '/'
},
{
text : 'Archives',
icon : <ArchiveOutlinedIcon />,
path : '/'
}
];
return (
<Box>
<Drawer
className={classes.drawer}
anchor="left" classes={{
paper: classes.drawerPaper
}}
open={mobileOpen}
onClose={handleDrawerToggle}
ModalProps={{
keepMounted: true, // Better open performance on mobile.
}}
sx={{
display: { xs: 'block', sm: 'none' },
flexShrink: 0,
'& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
}}
>
<Toolbar />
<Container>
<Typography variant="h5" component="h2" className={classes.title} gutterBottom>
My Account
</Typography>
</Container>
<Divider />
<List className={classes.list}>
{ list.map((item) => (
<ListItem key={item.text} className={classes.listItem} button>
<ListItemIcon className={classes.icon}>
{item.icon}
</ListItemIcon>
<ListItemText sx={{color: 'primary'}} primary={item.text} className={classes.text}/>
</ListItem>
))}
</List>
</Drawer>
</Box>
);
};
You have only included the drawer for xs - with display: { xs: 'block', sm: 'none' } that drawer will not display for any size but xs. You will need another drawer for sm and up. The MUI docs show a second drawer like this:
<Drawer
variant="permanent"
sx={{
display: { xs: 'none', sm: 'block' },
'& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
}}
open
>
{you would put your list stuff here}
</Drawer>
You will probably need to move the Toolbar component outside of the Drawer component.

How to set search image icon in react-native-google-places-autocomplete?

How to set search image icon in react-native-google-places-autocomplete?
I want to know how i can set search image icon on left side in react-native-google-places-autocomplete.
I want output like this in below screen.So please help me.
But my design is like this.
Here is code of DiscoveryLocation.js file.
import React, { Component } from 'react'
import { Text, View, TouchableOpacity, TextInput, StyleSheet, Image } from 'react-native'
import { heightPercentageToDP as hp, widthPercentageToDP as wp } from 'react-native-responsive-screen';
import { RFPercentage, RFValue } from "react-native-responsive-fontsize";
import MapView, { PROVIDER_GOOGLE, Marker } from 'react-native-maps';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
console.disableYellowBox = true;
export default class DiscoveryLocation extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.vwheader} >
<TouchableOpacity
onPress={() => { this.props.navigation.goBack() }}
>
<Image source={require('../../Images/left-arrow-red.png')} style={{ height: 25, width: 30, marginTop: 22, marginLeft: 15, }}
/>
</TouchableOpacity>
<Text style={styles.txtdisloc}>Discovery Location </Text>
</View>
<View style={styles.mapcontainer}>
<MapView
provider={PROVIDER_GOOGLE}
style={styles.map}
region={{
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.015,
longitudeDelta: 0.0121,
}}
>
</MapView>
<View style={{ marginTop: hp('12%'), }}>
<GooglePlacesAutocomplete
placeholder='Enter City, State, Country'
minLength={2} // minimum length of text to search
autoFocus={false}
fetchDetails={true}
onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
console.log(data);
console.log(details);
}}
getDefaultValue={() => {
return 'Mataram';
}}
query={{
// available options: https://developers.google.com/places/web-service/autocomplete
key: 'MY_API_KEY',
language: 'en', // language of the results
types: '(cities)' // default: 'geocode'
}}
styles={{
textInputContainer: {
width: wp('90%%'), height: hp('7%'), borderRadius: 11, borderTopWidth: 0,
borderBottomWidth: 0
},
textInput: {
marginLeft: 0,
marginRight: 0,
backgroundColor: 'D3D3D3'
},
description: {
fontWeight: 'bold',
},
predefinedPlacesDescription: {
color: '#1faadb'
},
powered: {
},
}}
filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities
predefinedPlacesAlwaysVisible={true}
/>
</View>
</View>
<View style={{ marginTop: 10, marginBottom: 10 }}>
<TouchableOpacity style={styles.btn}>
<Text style={styles.txtbtn}>Confirm Location</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
I know this is late, but for the future ref There are props to add icons in GooglePlacesAutocomplete
renderLeftButton={() => <Image source={require('path/custom/left-icon')} />}
renderRightButton={() => <Text>Custom text after the input</Text>}
Here is the link for tutorial

Need to dynamically add items into a drawer menu in React Native

I need to have some items dynamically in my app's drawer after some categories get fetched from a json file (https://www.rallyssimo.it/wp-json/wp/v2/categories)
json example (I need that information)
[
{
"id": 44,
.
.
"name": "ALTRI RALLY",
.
.
},
Tis is the drawer:
const CustomDrawerComponent = (props) => (
<SafeAreaView style={{flex:1}}>
<View style={{height:80, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center'}}>
<Image
source={{uri: 'https://www.rallyssimo.it/wp-content/uploads/2016/08/rallyssimo-logo.png'}}
style={{ height: 60, width: 180}}
/>
</View>
<ScrollView>
<DrawerItems {...props} />
</ScrollView>
</SafeAreaView>
)
const AppNavigator = createDrawerNavigator(
{
Home: DashboardStackNavigator,
},
{
contentComponent: CustomDrawerComponent
}
);
const AppContainer = createAppContainer(AppNavigator);
//Main class
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}
How can I put the items (I'm going to get from the JSON) in the drawer?
As you have noticed, you need to create your own custom drawer to achieve this, which is done with contentComponent: CustomDrawerComponent.
Now you cannot use DrawerItems within CustomDrawerComponent since you want full control on the items listed. But you can recreate the items yourself using basic and elements.
Finally you need to fetch the API and store the data in your state in order to render the result as a list in the drawer.
Here is a basic example for :
import React, { Component } from 'react';
import { ScrollView, Text, View, Image } from 'react-native';
import { NavigationActions } from 'react-navigation';
class CustomDrawerComponent extends Component {
constructor(props) {
super(props);
this.state = { data: null };
}
async componentDidMount() {
fetch('https://www.rallyssimo.it/wp-json/wp/v2/categories')
.then(res => res.json())
.then(data => this.setState({ data }))
}
navigateToScreen(routeName, params) {
return () => { this.props.navigation.dispatch(NavigationActions.navigate({ routeName, params })) };
}
render() {
if (this.state.data === null) {
return <Text>...</Text>;
}
return (
<View style={{ flex: 1, paddingTop: 30 }}>
<View style={{height:80, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center'}}>
<Image
source={{uri: 'https://www.rallyssimo.it/wp-content/uploads/2016/08/rallyssimo-logo.png'}}
style={{ height: 60, width: 180}}
/>
</View>
<ScrollView>
<View>
{this.state.data.map(x => (
<Text
key={x.id}
style={{ fontSize: 16, lineHeight: 30, textAlign: 'center' }}
onPress={this.navigateToScreen('page2')}
>
{x.name}
</Text>
))}
</View>
</ScrollView>
</View>
);
}
}
export default CustomDrawerComponent;
And here is a working snack.

React Native Opening Native Maps

I am trying to get my button onPress function to call a function that will open apple maps or google maps depending on the device. For some reason nothing is happening when I press the button.
Here is my function:
openMap= () => {
console.log('open directions')
Platform.select({
ios: () => {
Linking.openURL('http://maps.apple.com/maps?daddr=');
},
android: () => {
Linking.openURL('http://maps.google.com/maps?daddr=');
}
});
}
Here is the button:
<TouchableOpacity
onPress={this.openMap}
style={styles.navigateBtn}>
<Icon name="md-navigate" style={{ fontSize: 24 }} />
<Text
style={{ fontSize: 13, fontWeight: "700", lineHeight: 14 }}
>
NAVIGATE
</Text>
</TouchableOpacity>
Eventually I want to pass longitude and latitude into the openMap function to get directions but first I need to get the map to open.
Here is my import
import { View, TouchableOpacity, Modal, Platform, Alert, StyleSheet, Linking } from "react-native";
import {Header, Content, Text, Button, Icon, Card,CardItem, Title, Left, Right, Body, Container
} from "native-base";
import { Constants } from 'expo
Your button seem to call this.Map in the onPress of your TouchableOpacity. It should not be this.openMap ?
Hope it's help you!
EDIT:
Try to declare your function like this inside of your component:
openMap() {
console.log('open directions')
Platform.select({
ios: () => {
Linking.openURL('http://maps.apple.com/maps?daddr=');
},
android: () => {
Linking.openURL('http://maps.google.com/maps?daddr=');
}
});
}
And for your TouchableOpacity try this
<TouchableOpacity
onPress={() => this.openMap() }
style={styles.navigateBtn}>
<Icon name="md-navigate" style={{ fontSize: 24 }} />
<Text
style={{ fontSize: 13, fontWeight: "700", lineHeight: 14 }}
>
This will oepn maps in the web, then redirect to the app (if it is installed):
const openMaps = (latitude, longitude) => {
const daddr = `${latitude},${longitude}`;
const company = Platform.OS === "ios" ? "apple" : "google";
Linking.openURL(`http://maps.${company}.com/maps?daddr=${daddr}`);
}
Although i would just use this library, which uses deep linking instead:
openMap= () => {
console.log('open directions')
let f = Platform.select({
ios: () => {
Linking.openURL('http://maps.apple.com/maps?daddr=38.7875851,-9.3906089');
},
android: () => {
console.log('ANDROID')
Linking.openURL('http://maps.google.com/maps?daddr=38.7875851,-9.3906089').catch(err => console.error('An error occurred', err));;
}
});
f();
}

How to create Polyline using react-google-maps library

I am trying to plot Polyline between 4 GPS coordinates using react-google-maps library. Nothing is rendering on the map
import React from 'react';
import { withGoogleMap, GoogleMap, Marker, InfoWindow,Polyline } from 'react-google-maps';
class googleMapComponent extends React.Component {
//Higher order components: withGoogleMap is employed as a function call. This fucntion returns another component defination which is later mounted in render
// maintain a refernce to a map inside the component, so that
constructor(){
super()
this.state ={
map:null
}
}
mapMoved(){
console.log('mapMoved: ' + JSON.stringify(this.state.map.getCenter()))
}
mapLoaded(map){
//console.log('mapLoaded: ' + JSON.stringify(map.getCenter()))
if(this.state.map !==null)
return
this.setState({
map:map
})
}
zoomchanged(){
console.log('mapZoomed: ' + JSON.stringify(this.state.map.getZoom()))
}
handleMarkerClick(targetMarker) {
this.setState({
markers: this.state.markers.map(marker => {
if (marker === targetMarker) {
return {
...marker,
showInfo: true,
};
}
return marker;
}),
});
}
handleMarkerClose(targetMarker) {
this.setState({
markers: this.state.markers.map(marker => {
if (marker === targetMarker) {
return {
...marker,
showInfo: false,
};
}
return marker;
}),
});
}
render() {
const markers= [
{
position: new google.maps.LatLng(36.05298766, -112.0837566),
showInfo: false,
infoContent: false,
},
{
position: new google.maps.LatLng(36.21698848, -112.0567275),
showInfo: false,
infoContent: false,
},
]
const lineCoordinates= [
{coordinate: new google.maps.LatLng(36.05298766, -112.0837566)},
{coordinate: new google.maps.LatLng(36.0529832169413, -112.083731889724)},
{coordinate: new google.maps.LatLng(36.0529811214655, -112.083720741793)},
{coordinate: new google.maps.LatLng(36.0529811214655, -112.083720741793)},
]
return (
<GoogleMap
ref={this.mapLoaded.bind(this)}
onDragEnd={this.mapMoved.bind(this)}
onZoomChanged={this.zoomchanged.bind(this)}
defaultZoom={this.props.zoom}
defaultCenter={this.props.center}
>
{markers.map((marker, index) => (
<Marker
position={marker.position}
title="click on it Sir..!!"
defaultPosition={this.props.center}
style={{height: '2xpx', width: '2px'}}
/>
))}
{lineCoordinates.map((polyline,index)=>(
<Polyline
defaultPosition={this.props.center}
path= {polyline.coordinate}
geodesic= {true}
strokeColor= {#FF0000}
strokeOpacity= {1.0}
strokeWeight= {2}
/>
</GoogleMap>
)
}
}
export default withGoogleMap(googleMapComponent);
Any suggestion on it will be helpful. If the library does not support this functionality. I can swtich the library too.
Yes. Example:
render() {
const pathCoordinates = [
{ lat: 36.05298765935, lng: -112.083756616339 },
{ lat: 36.2169884797185, lng: -112.056727493181 }
];
return (
<GoogleMap
defaultZoom={this.props.zoom}
defaultCenter={this.props.center}
>
{/*for creating path with the updated coordinates*/}
<Polyline
path={pathCoordinates}
geodesic={true}
options={{
strokeColor: "#ff2527",
strokeOpacity: 0.75,
strokeWeight: 2,
icons: [
{
icon: lineSymbol,
offset: "0",
repeat: "20px"
}
]
}}
/>
</GoogleMap>
);
}
When you run the mapping function, are you creating a new polyline for each set of coordinates? Looking at the Google Maps docs, the polyline takes an array of objects as a path argument. google-maps-react is just a wrapper around that API, so you should be able to create your polyline just by passing in the array of objects as the path. Currently, you're trying to generate a bunch of polyline objects based on tiny coordinate fragments.
A simpler example to show just one polyline being drawn:
<GoogleMap defaultZoom={7} defaultCenter={{ lat: -34.897, lng: 151.144 }}>
<Polyline path={[{ lat: -34.397, lng: 150.644 }, { lat: -35.397, lng: 151.644 }]}/>
</GoogleMap>
Entire snippet for anyone unclear about the correct imports and setup (with recompose):
import React from "react";
import ReactDOM from "react-dom";
import { compose, withProps } from "recompose";
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker,
Polyline
} from "react-google-maps";
const MyMapComponent = compose(
withProps({
googleMapURL:
"https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&v=3.exp&libraries=geometry,drawing,places",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px` }} />,
mapElement: <div style={{ height: `100%` }} />
}),
withScriptjs,
withGoogleMap
)(props => (
<GoogleMap defaultZoom={7} defaultCenter={{ lat: -34.897, lng: 151.144 }}>
<Polyline path={[{ lat: -34.397, lng: 150.644 }, { lat: -35.397, lng: 151.644 }]}/>
</GoogleMap>
));
ReactDOM.render(<MyMapComponent />, document.getElementById("root"));
Same example as above, without recompose:
import React from "react";
import ReactDOM from "react-dom";
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Polyline
} from "react-google-maps";
const InternalMap = props => (
<GoogleMap defaultZoom={7} defaultCenter={{ lat: -34.897, lng: 151.144 }}>
<Polyline
path={[{ lat: -34.397, lng: 150.644 }, { lat: -35.397, lng: 151.644 }]}
/>
</GoogleMap>
);
const MapHoc = withScriptjs(withGoogleMap(InternalMap));
const MyMapComponent = props => (
<MapHoc
googleMapURL="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&v=3.exp&libraries=geometry,drawing,places"
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
);
ReactDOM.render(
<MyMapComponent />,
document.getElementById("root")
);