Access to XMLHttpRequest at ‘https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.0427136,13.7101312&radius=10000&key=A’ from origin ‘http://localhost:64496’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
I am getting this error when i am trying to access the nearby places in web based app, using google map API call. It works fine when i am trying to run the project on Andriod emulator.
I dont know what should i change in order to fix the problem.
I tried creating a proxy server using node and then running it. still i got the same error. When i try to access the direct link in chrome i get the jason file of nearby places but its not displaying in the app
const express = require('express');
const request = require('request');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/api/places', (req, res) => {
const { lat, lng, radius } = req.query;
if (!lat || !lng || !radius) {
return res.status(400).json({ error: 'Latitude, longitude, and radius parameters are required' });
}
const apiKey = process.env.GOOGLE_API_KEY;
const url = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${lat},${lng}&key=${apiKey}`;
request(url, (error, response, body) => {
if (!error && response.statusCode == 200) {
res.json(JSON.parse(body));
} else {
res.status(response.statusCode).json({ error: 'Failed to fetch data from Google API' });
}
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
This is how i am calling the nearby places-
Future<List<dynamic>> getNearbyPlaces(
double lat, double lng, double radius) async {
final url =
'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$lng&radius=$radius&key=$apiKey';
try {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
final result = json.decode(response.body);
return result['results'];
} else {
print(
'Failed to load nearby places: ${response.statusCode} - ${response.body}');
throw Exception('Failed to load nearby places');
}
} catch (e) {
print('Error in getNearbyPlaces: $e');
rethrow;
}
}
Future<void> _getCurrentLocation(
maps_flutter.GoogleMapController controller) async {
try {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high); // Get current position
controller.animateCamera(maps_flutter.CameraUpdate.newCameraPosition(
maps_flutter.CameraPosition(
target: maps_flutter.LatLng(position.latitude, position.longitude),
zoom: 15,
),
));
_getNearbyPlaces(
position.latitude, position.longitude); // Get nearby places
} catch (e) {
print('Error getting current location: $e');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error getting current location')),
);
}
}
Future<void> _searchLocation(String query) async {
try {
final result = await _geocodingService
.getCoordinates(query); // Get coordinates for query
if (result != null) {
final maps_flutter.GoogleMapController controller =
await _controller.future;
controller.animateCamera(maps_flutter.CameraUpdate.newCameraPosition(
maps_flutter.CameraPosition(
target: maps_flutter.LatLng(result['lat'], result['lng']),
zoom: 14.4746,
),
));
_getAttractionsInCity(query); // Get attractions in city
setState(() {
_searchHistory.add(query);
_filteredSearchHistory.clear();
});
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Location not found')),
);
}
} catch (e) {
print('Error searching location: $e');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error searching location')),
);
}
}
Future<void> _getNearbyPlaces(double lat, double lng) async {
try {
final places = await _placesService.getNearbyPlaces(
lat, lng, _searchRadius); // Get nearby places
setState(() {
_places = places;
_markers = places
.map((place) => maps_flutter.Marker(
markerId: maps_flutter.MarkerId(place['place_id']),
position: maps_flutter.LatLng(
place['geometry']['location']['lat'],
place['geometry']['location']['lng']),
infoWindow: maps_flutter.InfoWindow(
title: place['name'],
snippet: place['vicinity'],
),
icon: BitmapDescriptor.defaultMarkerWithHue(
BitmapDescriptor.hueRed),
))
.toList();
});
} catch (e) {
print('Error getting nearby places: $e');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error getting nearby places')),
);
}
}
Future<void> _getAttractionsInCity(String city) async {
try {
final places = await _placesService
.getAttractionsInCity(city); // Get attractions in city
setState(() {
_places = places;
_markers = places
.map((place) => maps_flutter.Marker(
markerId: maps_flutter.MarkerId(place['place_id']),
position: maps_flutter.LatLng(
place['geometry']['location']['lat'],
place['geometry']['location']['lng']),
infoWindow: maps_flutter.InfoWindow(
title: place['name'],
snippet: place['formatted_address'],
),
icon: BitmapDescriptor.defaultMarkerWithHue(
BitmapDescriptor.hueRed),
))
.toList();
});
} catch (e) {
print('Error getting attractions in city: $e');
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error getting attractions in city')),
);
}
}
This is my code for nearby places and if i search any city in search bar. I failed to get the attraction
Birdy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.