Skip to content

Instantly share code, notes, and snippets.

@juhahinkula
Created April 25, 2018 07:44
Show Gist options
  • Select an option

  • Save juhahinkula/af5a6385b209e914f84246f203e12bb4 to your computer and use it in GitHub Desktop.

Select an option

Save juhahinkula/af5a6385b209e914f84246f203e12bb4 to your computer and use it in GitHub Desktop.
import React from 'react';
import { StyleSheet, Text, View, Alert, TextInput, Button } from 'react-native';
import { MapView } from 'expo';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
address: '',
region: {latitude: 60.200692, longitude: 24.934302, latitudeDelta: 0.032, longitudeDelta: 0.02},
restaurants: []
};
}
// Fetch coordinates from the Google API and show the address in the map
// Use Google geocoding API
showAddress = () => {
const url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + this.state.address + '&key=AIzaSyBKwL3M2YKl1vlYxx66C2SnP-qjwIR1fXY';
fetch(url)
.then((response) => response.json())
.then((responseData) => {
const lat = responseData.results[0].geometry.location.lat;
const lon = responseData.results[0].geometry.location.lng;
this.setState({region: {latitude: lat, longitude: lon, latitudeDelta: 0.0312, longitudeDelta: 0.0211}});
})
.then(() => {
this.showRestaurants();
});
}
// Show nearby restaurants
// Use Google places API
showRestaurants = () => {
const url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + this.state.region.latitude + ',' + this.state.region.longitude + '&radius=500&type=restaurant&key=AIzaSyAFkmPmVZrS8AKOvZd4x94LZU48Hh4kdMk';
fetch(url)
.then((response) => response.json())
.then((responseData) => {
this.setState({restaurants: responseData.results});
});
}
onRegionChange(region) {
this.setState({ region });
}
render() {
return (
<View style={styles.container}>
<MapView
style={{flex: 5}}
region={this.state.region}
onRegionChange={this.onRegionChange} >
{this.state.restaurants.map((marker, index) => (
<MapView.Marker
key={index}
coordinate={{latitude: marker.geometry.location.lat, longitude: marker.geometry.location.lng}}
title={marker.name}
description={marker.vicinity}
/>
))}
</MapView>
<View style={styles.container}>
<TextInput placeholder='Type address' style={{height: 40, fontSize: 18}} onChangeText={(address) => this.setState({address})} />
<Button title="Show" onPress={this.showAddress} />
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment