I am new to using Getstate and UseState
Normally this works when i hard code the longitude and latitude its fine, now i want to get the longitude and latitude directly from an entered address.
i have set the values to setstate, but i am new to using setstate , use state.
I have written a Method that should get the address. So upon getting the address should resolve to getting the Longitude / latitude
This gets the Longitude and Latitude Well
GetLongitudeFromAddress = (txtaddress) =>{
let address = txtaddress;
let lng = this.state.Alongitude;
let lat = this.state.Alatitude;
var logLatApi = 'https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false&key=AIzaSyBsy6x3mTXbPQ52qk6XMI9u1NgMfn9-YNE';
var header = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
fetch(
logLatApi,{
method : 'GET',
headers : header
}
).then((response) => response.json())
.then((responseJson)=>{
if(responseJson.status ==='OK')
{
this.setState({longitude: responseJson.results[0].geometry.location.lng});
this.setState({latitude: responseJson.results[0].geometry.location.lat});
}
})
}
Now I want to use this in my setstate / usestate here
const [coordinates] = useState([
{
latitude: 6.450430,
longitude: 3.390460,
},
{
latitude: 6.430980,
longitude: 3.435880,
},
]);
How can I do this? My code in full looks like this :
import React , {useState} from 'react';
import {StyleSheet, View, Dimensions, TextInput} from 'react-native';
import MapView , { Marker , Polyline } from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
this.state = {
Address : '',
Alongitude : '',
Alatitude: '',
};
GetLongitudeFromAddress = (txtaddress) =>{
let address = txtaddress;
let lng = this.state.Alongitude;
let lat = this.state.Alatitude;
var logLatApi = 'https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false&key=AIzaSyBsy6x3mTXbPQ52qk6XMI9u1NgMfn9-YNE';
var header = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
fetch(
logLatApi,{
method : 'GET',
headers : header
}
).then((response) => response.json())
.then((responseJson)=>{
if(responseJson.status ==='OK')
{
this.setState({longitude: responseJson.results[0].geometry.location.lng});
this.setState({latitude: responseJson.results[0].geometry.location.lat});
}
})
}
const ShowMap =() =>{
const [coordinates] = useState([
{
latitude: 6.450430,
longitude: 3.390460,
},
{
latitude: 6.430980,
longitude: 3.435880,
},
]);
return(
<View style={styles.container}>
<MapView
style={styles.maps}
initialRegion={{
latitude: coordinates[0].latitude,
longitude: coordinates[0].longitude,
latitudeDelta: 0.0622,
longitudeDelta: 0.0121,
}}>
<MapViewDirections
origin={coordinates[0]}
destination={coordinates[1]}
apikey="AIzaSyBsy6x3mTXbPQ52qk6XMI9u1NgMfn9-YNE"
strokeWidth={4}
strokeColor="#FD0631"
/>
<Marker coordinate={coordinates[0]} />
<Marker coordinate={coordinates[1]} />
</MapView>
<View style={styles.inputView}>
<TextInput
style={styles.input}
placeholder="Origin"
onChange={this.GetLongitudeFromAddress()}
/>
<TextInput
style={styles.input}
placeholder="Destination"
onChange={this.GetLongitudeFromAddress()}
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
maps: {
width: Dimensions.get('screen').width,
height: Dimensions.get('screen').height,
},
inputView:{
backgroundColor: 'rgba(0,0,0,0)',
position: 'absolute',
top: 0,
left: 5,
right: 5
},
input: {
height: 50,
padding: 10,
marginTop: 20,
marginLeft: 10,
marginRight: 10,
fontSize: 18,
borderWidth: 1,
borderRadius: 35,
borderColor: '#EEEEEE',
backgroundColor: 'white',
}
});
export default ShowMap;
Please assist I am a bit confused here. I just need it to dynamically get it and show directions in the map.
To start off, you need a new hook, to get your API to run. Achieve this by using useEffect.
UseEffect with an empty array dependency will only run your API once on load. With the results from the API, use the set method from useState to update the Coordinates variable. You may then see the Coordinates updated dynamically.
const ShowMap =() =>{
const [Coordinates, setCoordinates] = useState();
useEffect(() => {
(async () => {
const result = GetLongitudeFromAddress(param);
setCoordinates(result);
})();
}, []);
return (<Map/>)
}
Related
I am a little knew the react native, and I am not so familiar with react native permissions with expo. This is my code for the MapView component.
import MapView, { Marker, Callout } from 'react-native-maps';
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Modal, Button } from 'react-native';
import * as Location from 'expo-location';
export default function Map(props) {
let handler = props.handler;
let show = props.show;
const [location, setLocation] = useState({coords: {longitude: 0, latitude: 0}});
const [errorMsg, setErrorMsg] = useState(null);
useEffect(() => {
(async () => {
let { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
return;
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location);
})();
});
let text = "wating...";
if (errorMsg) {
text = errorMsg;
}
return (
<Modal animationType = 'slide' transparent = {true} visible = {show}>
<View style={styles.container}>
<Button title = 'CLOSE' color = 'white' onPress = {handler}/>
<MapView
showUserLocation = {true}
style={styles.map}
initialRegion={{
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
>
<Marker coordinate = {{latitude: location.coords.latitude,
longitude: location.coords.longitude}} pinColor = 'black'>
<Callout>
<Text>Im here</Text>
</Callout>
</Marker>
</MapView>
</View>
</Modal>
);
}
const styles = StyleSheet.create({
container: {
height: '80%',
margin: 10,
marginTop: '30%',
padding: 10,
paddingTop: 0,
backgroundColor: '#2997FF',
borderRadius: 10,
justifyContent: 'space-between',
alignItems: 'center'
},
map: {
width: '100%',
height: '92%',
},
paragraph: {
margin: 50
}
});
I can't find a clear answer on how to add permissions even after checking the docs and a lot of videos. This module seems to work well with react native cli.
Location.js
export async function requestPermission() {
RNLocation.configure({
distanceFilter: 5.0
})
var permission = await RNLocation.requestPermission({
ios: 'whenInUse', // or 'always'
android: {
detail: 'coarse', // or 'fine'
rationale: {
title: "We need to access your location",
message: "We use your location to show where you are on the map",
buttonPositive: "OK",
buttonNegative: "Cancel"
}
}
});
return permission;
}
Main.js
useEffect(() => {
async function fetchLocation() {
var permission = await requestPermission();
if (permission) {
var location = await requestLocation();
const { coords } = location;
setLocation(coords)
} else {
dispatch(toastMessage({
message: 'Permission to access location was denied',
title: APPLICATION_NAME,
type: 'error',
}))
return
}
}
fetchLocation();
}, [])
here example see
Hope this will help you
I want to get the directions from 2 points (origin and destination)
i have written a simple function to get longitude and latitude.
it looks like this
const GetLongitudeFromAddress = (address) =>{
var logLatApi = 'https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false&key=AIzaSyBsy6x3mTXbPQ52qk6XMI9u1NgMfn9-YNE';
var header = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
fetch(
logLatApi,{
method : 'GET',
headers : header
}
).then((response) => response.json())
.then((responseJson)=>{
if(responseJson.status ==='OK')
{
this.setState({longitude: responseJson.results[0].geometry.location.lng});
this.setState({latitude: responseJson.results[0].geometry.location.lat});
}
})
}
Now i want to use it in inputText Like this
<TextInput
style={styles.input}
placeholder="Origin"
onChangeText={text => GetLongitudeFromAddress(text)}
/>
it does not seem to work, i get this As error possible promised handled rejection which looks like this image below
How can I use this with useState? My code is looking like this below :
import React , {useState, useEffect} from 'react';
import {StyleSheet, View, Dimensions, TextInput} from 'react-native';
import MapView , { Marker , Polyline } from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
const ShowMap =() =>{
const GetLongitudeFromAddress = (address) =>{
var logLatApi = 'https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false&key=AIzaSyBsy6x3mTXbPQ52qk6XMI9u1NgMfn9-YNE';
var header = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
fetch(
logLatApi,{
method : 'GET',
headers : header
}
).then((response) => response.json())
.then((responseJson)=>{
if(responseJson.status ==='OK')
{
this.setState({longitude: responseJson.results[0].geometry.location.lng});
this.setState({latitude: responseJson.results[0].geometry.location.lat});
}
})
}
const [coordinates] = useState([
{
latitude: 6.450430,
longitude: 3.390460,
},
{
latitude: 6.430980,
longitude: 3.435880,
},
]);
return(
<View style={styles.container}>
<MapView
style={styles.maps}
initialRegion={{
latitude: coordinates[0].latitude,
longitude: coordinates[0].longitude,
latitudeDelta: 0.0622,
longitudeDelta: 0.0121,
}}>
<MapViewDirections
origin={coordinates[0]}
destination={coordinates[1]}
apikey="AIzaSyBsy6x3mTXbPQ52qk6XMI9u1NgMfn9-YNE"
strokeWidth={4}
strokeColor="#FD0631"
/>
<Marker coordinate={coordinates[0]} />
<Marker coordinate={coordinates[1]} />
</MapView>
<View style={styles.inputView}>
<TextInput
style={styles.input}
placeholder="Origin"
onChangeText={text => GetLongitudeFromAddress(text)}
/>
<TextInput
style={styles.input}
placeholder="Destination"
onChangeText={text => GetLongitudeFromAddress(text)}
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
maps: {
width: Dimensions.get('screen').width,
height: Dimensions.get('screen').height,
},
inputView:{
backgroundColor: 'rgba(0,0,0,0)',
position: 'absolute',
top: 0,
left: 5,
right: 5
},
input: {
height: 50,
padding: 10,
marginTop: 20,
marginLeft: 10,
marginRight: 10,
fontSize: 18,
borderWidth: 1,
borderRadius: 35,
borderColor: '#EEEEEE',
backgroundColor: 'white',
}
});
export default ShowMap;
How do i go about this? How Can I use this GetLongitudeFromAddress to get the longitude and latitude from both feilds. Kindly assist
You need to have a button that will call the function GetLongitudeFromAddress when pressed. Calling this function every change of your input text value will be costly as it will call geocoding requests everytime the function is called.
I successfully modified your code to get the address from the input text then convert it using the function, then use the converted coordinates as input to MapViewDirections. Here's a sample code and a code snippet below with inline comments:
import React, { useState, useEffect } from 'react';
import { StyleSheet, View, Dimensions, TextInput, Button } from 'react-native';
import MapView, { Marker, Polyline } from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
const { width, height } = Dimensions.get('window');
const ShowMap = () => {
//initial maps coordinate
const [initialCenter] = useState({
latitude: 6.45043,
longitude: 3.39046,
});
//state variables for the value of the textbox
const [originInput, setOInput] = useState(null);
const [destInput, setDInput] = useState(null);
//state variables to handle the coordinates after getting it from GetLongitudeFromAddress function
const [originReq, setOReq] = useState(null);
const [destReq, setDReq] = useState(null);
//state variable that will be one of the condition to trigger MapViewDirections once button is pressed
const [isBtnPressed, setBtn] = useState(null);
//state variable that will be a condition to show the origin and destination marker once the route was started
const [routeStarted, setRouteStarted] = useState(null);
//function that will convert the address from your inpput textbox to a coordinate(geocoding)
//coord variable will be the variable that will determine if you are converting the origin or the destination coordinates
const GetLongitudeFromAddress = (address, coord) => {
var logLatApi =
'https://maps.googleapis.com/maps/api/geocode/json?address=' +
address +
'&sensor=false&key=YOUR_KEY';
var header = {
Accept: 'application/json',
'Content-Type': 'application/json',
};
fetch(logLatApi, {
method: 'GET',
headers: header,
})
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.status === 'OK') {
//check if coord value is 'origin' or destination'
if (coord == 'origin' || coord == 'destination') {
if (coord == 'origin') {
//if origin, it will change the originReq state value to the result
setOReq({
latitude: responseJson.results[0].geometry.location.lat,
longitude: responseJson.results[0].geometry.location.lng,
});
} else {
//if destination, it will change the destReq state value to the result
setDReq({
latitude: responseJson.results[0].geometry.location.lat,
longitude: responseJson.results[0].geometry.location.lng,
});
}
}
}
});
};
//function called when the button is pressed
const processAddress = () => {
//it will pass the current value of your input state and hardcoding origin or destination to mark if the address being converted to coordinates is either one of them
GetLongitudeFromAddress(originInput, 'origin');
GetLongitudeFromAddress(destInput, 'destination');
//change isBtnPressed state variable value
setBtn('Y');
};
//function called when the route is ready, it will also fit the polyline to the current view
const routeReady = (result) => {
console.log(`Distance: ${result.distance} km`);
console.log(`Duration: ${result.duration} min.`);
console.log(isBtnPressed);
this.mapView.fitToCoordinates(result.coordinates, {
edgePadding: {
right: width / 20,
bottom: height / 20,
left: width / 20,
top: height / 20,
},
});
};
return (
<View style={styles.container}>
<MapView
style={styles.maps}
ref={(c) => (this.mapView = c)}
initialRegion={{
latitude: initialCenter.latitude,
longitude: initialCenter.longitude,
latitudeDelta: 0.0622,
longitudeDelta: 0.0121,
}}>
{isBtnPressed !== null && originReq !== null && destReq !== null && (
<MapViewDirections
origin={originReq}
destination={destReq}
apikey="YOUR_KEY"
strokeWidth={4}
strokeColor="#FD0631"
onStart={() => {
setRouteStarted('Y');
}}
onReady={(result) => {
routeReady(result);
}}
onError={() => {
setRouteStarted(null);
}}
/>
)}
{routeStarted !== null && originReq != null && (
<Marker coordinate={originReq} />
)}
{routeStarted !== null && destReq != null && (
<Marker coordinate={destReq} />
)}
</MapView>
<View style={styles.inputView}>
<TextInput
style={styles.input}
placeholder="Origin"
onChangeText={(text) => setOInput(text)}
/>
<TextInput
style={styles.input}
placeholder="Destination"
onChangeText={(text) => setDInput(text)}
/>
<Button title="Press me" color="#f194ff" onPress={processAddress} />
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
maps: {
width: Dimensions.get('screen').width,
height: Dimensions.get('screen').height,
},
inputView: {
backgroundColor: 'rgba(0,0,0,0)',
position: 'absolute',
top: 0,
left: 5,
right: 5,
},
input: {
height: 50,
padding: 10,
marginTop: 20,
marginLeft: 10,
marginRight: 10,
fontSize: 18,
borderWidth: 1,
borderRadius: 35,
borderColor: '#EEEEEE',
backgroundColor: 'white',
},
});
export default ShowMap;
Note: Kindly remove your API key in your code and please don't share it to public sites to protect your API key from unexpected usage.
I am using React Native with Expo and this was originally a class based component but I converted it to a functional component because I want to use hooks. Now it is throwing an error shown in the screenshot. I am not sure what to do about the error?I have seen one other posting about this, but was a little lost (I am practicing with react). The component is basically a GPS with a marker! Thank you
import { View, Text, Animated, StyleSheet } from "react-native";
import MapView, { Marker, PROVIDER_GOOGLE } from "react-native-maps";
import React, { Component, useState } from "react";
import { MaterialCommunityIcons } from "react-native-vector-icons";
const LATITUDE = 18.7934829;
const LONGITUDE = 98.9867401;
const LATITUDE_DELTA = 0.009;
const LONGITUDE_DELTA = 0.009;
export default function MapLocation() {
const [location, setLocation] = useState({
isLoading: true,
latitude: LATITUDE,
longitude: LONGITUDE,
error: null,
});
var getMapRegion = () => ({
latitude: location.latitude,
longitude: location.longitude,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
});
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
setLocation({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => setLocation({ error: error.message }),
{ enableHighAccuracy: false, timeout: 200000, maximumAge: 1000 }
);
navigator.geolocation.watchPosition((position) => {
const { latitude, longitude } = position.coords;
setLocation({ latitude, longitude });
});
const { isLoading } = location;
return (
<View style={{ flex: 1 }}>
<MapView
style={{ flex: 1 }}
provider={PROVIDER_GOOGLE}
region={getMapRegion}
showsUserLocation={true}
showsMyLocationButton={true}
>
<Marker coordinate={getMapRegion}>
<MaterialCommunityIcons name="egg" color={"white"} size={35} style={styles.shadow} />
</Marker>
<Marker
coordinate={{ latitude: 34.0198536, longitude: -80.923467 }}
pinColor="maroon"
title={"title"}
description={"description"}
>
<MaterialCommunityIcons name="school" color={"maroon"} size={40} style={styles.shadow} />
</Marker>
</MapView>
</View>
);
}
const styles = StyleSheet.create({
shadow: {
// transform: [{ rotateZ: "10deg" }],
shadowColor: "black",
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.5,
shadowRadius: 2,
elevation: 3,
},
});
There were several problems with my conversion to hooks using useState and useEffect. Both of which I solved with this guide on converting classes to functions. I was not using the "useEffect hook" in place of component did mount, I also did not have an empty array at the end of the useEffect hook which made it re-render constantly from what I understand.
Link to functional component conversion steps
Unable to drag the map around, after using google auto complete to search for the location. The map is able to change to the location. However I am unable to drag the map around, its stuck to the center of the location that I searched.
MapContainer.js is used to render the map and componentdidmount is used to retrieve the coordinates of busstops which will be displayed as markers under the render below
import { View } from "react-native";
import MapInput from "./MapInput";
import { getLocation, geocodeLocationByName } from "./location-service";
import React, { Component } from "react";
import MapView, { Marker, StyleSheet } from "react-native-maps";
const MyMapView = (props) => {
return (
<MapView
style={{ flex: 1 }}
region={props.region}
showsUserLocation={true}
onRegionChange={(reg) => props.onRegionChange(reg)}
>
{props.busstopArray.map((item) => {
return (
<Marker
key={item.bus_stop_id}
coordinate={{
latitude: Number(item.latitude),
longitude: Number(item.longitude),
}}
title={item.name}
></Marker>
);
})}
</MapView>
);
};
class MapContainer extends React.Component {
state = {
region: {},
busstop: [], //busstop is an empty array, in which the JSON values will be added, to be used later in the code.
};
componentDidMount() {
this.getInitialState();
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ route_id: "1" }, { route_id: "2" }),
};
fetch(
"https://laravelsyd-fypfinalver.herokuapp.com/getBusStop",
requestOptions
)
.then((response) => response.json())
.then((data) => {
this.setState({ busstop: data });
});
}
getInitialState() {
getLocation().then((data) => {
//import locationservice
console.log(data); //prints out intial region coords
this.setState({
region: {
latitude: data.latitude,
longitude: data.longitude,
latitudeDelta: 0.003,
longitudeDelta: 0.003,
},
});
});
}
getCoordsFromName(loc) {
this.setState({
region: {
latitude: loc.lat,
longitude: loc.lng,
latitudeDelta: 0.003,
longitudeDelta: 0.003,
},
});
}
onMapRegionChange(region) {
this.setState({ region });
}
render() {
const bus_stop = [...this.state.busstop];
// console.log(bus_stop); //testing to see if can display the json objects and it can
return (
<View style={{ flex: 1 }}>
<View style={{ flex: 1 }}>
<MapInput notifyChange={(loc) => this.getCoordsFromName(loc)} />
</View>
{this.state.region["latitude"] ? (
<View style={{ flex: 1 }}>
<MyMapView
region={this.state.region}
onRegionChange={(reg) => this.onMapRegionChange(reg)}
busstopArray={bus_stop}
/>
</View>
) : null}
</View>
);
}
}
export default MapContainer;
you have to add draggable in Marker:
<Marker
draggable
coordinate={{
latitude: Number(this.state.location.latitude),
longitude: Number(this.state.location.longitude),
}}
onDragEnd={e =>
this.setState({location: e.nativeEvent.coordinate})
}
/>
Problem:
I am creating react native app with Google map integration. This is how I have done It.
import React, { Component } from "react";
import { View, Text, StyleSheet, Dimensions } from "react-native";
import { MapView } from "expo";
import Marker from "./Marker";
class Parking extends Component {
static navigationOptions = {
title: "Parking",
headerStyle: {
backgroundColor: "#06153b"
},
headerTintColor: "#fff",
headerTitleStyle: {
color: "#ffff"
}
};
constructor(props) {
super(props);
this.state = {
focusedLocation: {
latitude: 0,
longitude: 0,
latitudeDelta: 0.0122,
longitudeDelta:
(Dimensions.get("window").width / Dimensions.get("window").height) *
0.0122
},
locationChosen: false,
placesList: []
};
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(
pos => {
const coordsEvent = {
nativeEvent: {
coordinate: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude
}
}
};
this.pickLocationHandler(coordsEvent);
},
err => {
console.log(err);
alert("Fetching the Position failed");
}
);
}
pickLocationHandler = event => {
const coords = event.nativeEvent.coordinate;
let placesList = [];
let places = [];
this.map.animateToRegion({
...this.state.focusedLocation,
latitude: coords.latitude,
longitude: coords.longitude
});
const apikey = "My API key";
fetch(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" +
coords.latitude +
"," +
coords.longitude +
"&radius=500" +
"&type=parking" +
"&key=" +
apikey
)
.then(response => response.json())
.then(responseJson => {
if (responseJson) {
placesList = responseJson.results;
console.log(placesList);
placesList.map((el, index) => {
const place = {
title: el.name,
coordinates: {
latitude: el.geometry.location.lat,
longitude: el.geometry.location.lng
}
};
places[index] = place;
});
}
});
if (places) {
this.setState({ placesList: places });
console.log(places);
}
this.setState({ locationChosen: true });
};
render() {
let marker = null;
if (this.state.locationChosen) {
marker = <MapView.Marker coordinate={this.state.focusedLocation} />;
}
const places = this.state.placesList;
return (
<View style={styles.container}>
<MapView
initialRegion={this.state.focusedLocation}
showsUserLocation={true}
style={styles.map}
onPress={this.pickLocationHandler}
ref={ref => (this.map = ref)}
>
{places.map((place, index) => {
<MapView.Marker
coordinate={place.coordinates}
title={place.title}
/>;
})}
{marker}
</MapView>
</View>
);
}
}
export default Parking;
const styles = StyleSheet.create({
container: {
width: "100%",
alignItems: "center",
paddingBottom: 10,
paddingLeft: 10,
paddingRight: 10,
paddingTop: 10
// backgroundColor:"#192f6a"
},
map: {
height: "100%",
width: "100%"
},
button: {
margin: 8
}
});
But It is showing Nothing On the Map. When I console log the places Like this.
if (places) {
this.setState({ placesList: places });
console.log(places);
}
It shows an Empty array. If I console log the placesList inside the fetch it shows the results. Can Someone help me to solve this problem and To modify My code in order to show the markers for the places that I have got from the fetch result from google API in the map?. Thank You very Much!!.
I'm fairly new to all this but I would say a couple of things:
1 - You're declaring 'place' as a const const place = ... but you're also trying to update it within the map loop, so I'm guessing that won't work. Use var place = ... instead?
2 - Instead of places[index] = place, does places.push(place) work?