React Google Maps Street View Panorama onCloseclick not firing - javascript

I'm using the StreetViewPanorama from react-google-maps/api. It comes with an onCloseclick prop that accepts a callback that supposedly fires when the close button is clicked. However, it is not firing whatever I do. Any advice?
<GoogleMap
zoom={15}
center={data.position}
mapContainerClassName="map-container"
>
<StreetViewPanorama
options={{
position: data.position,
visible: true,
}}
onCloseclick={(e) => {
console.log(e); // this is not console logging anything
}}
/>
</GoogleMap>

Related

How to embed an exact place on google maps in Reactjs

I am redoing my website with Reactjs. I'm trying to embed an exact google place with reviews on the map so it would look like this (My website written with wordpress)
So far I could only display a pin with exact coordinates, and it would look like this
Is there a way to embed an exact place on the maps as the reviews are very important to be visible for my customers?
If I would copy the link with the embedded place like this
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d12063.71295670172!2d-72.388377!3d40.895389!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x46289ec3b50eabb9!2sMove%20Plus!5e0!3m2!1sen!2sus!4v1613186587593!5m2!1sen!2sus" width="600" height="450" frameborder="0" style="border:0;" allowfullscreen="" aria-hidden="false" tabindex="0"></iframe> into my function, the website would crash.
Here's my google maps component :
import React from "react";
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker,
} from "react-google-maps";
const MapWrapper = withScriptjs(
withGoogleMap((props) => (
<GoogleMap
defaultZoom={13}
defaultCenter={{ lat: 40.895436, lng: -72.388484 }}
>
<Marker position={{ lat: 40.895436, lng: -72.388484 }} />
</GoogleMap>
))
);
function MyMap() {
return (
<>
<MapWrapper
googleMapURL="https://maps.googleapis.com/maps/api/myAPIHere"
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `100%` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</>
);
}
export default MyMap;
The map from the screenshot you want to achieve is using Maps Embed API while the "react-google-maps" library in your code is using Maps JavaScript API. These APIs are different and if you want to achieve the one from your screenshot in Reactjs, you can put the directly inside the div that you want to display. You can generate the iframe of your place you can check this link. Just search for your place and it will generate the iframe. Please note that there's a key parameter in the iframe link. This means that you need to put an API key in your request.
Here is a sample code and code snippet below:
import React from "react";
import ReactDOM from "react-dom";
function App() {
return (
<div>
<h1>MAPS!</h1>
<p>Please see map below</p>
<iframe
width="600"
height="450"
style={{ border: 0 }}
loading="lazy"
allowfullscreen
src="https://www.google.com/maps/embed/v1/place?q=place_id:ChIJ92pXbcOV6IkRuasOtcOeKEY&key=YOUR_API_KEY"
/>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
Here is a code below:
function initMap() {
var mapOptions, map, marker,infoWindow = '',
element = document.getElementById( 'map-canvas' );
mapOptions = {
zoom: 8,
center: new google.maps.LatLng( 0,0 ),
disableDefaultUI: false, // Disables the controls like zoom control on the map if set to true
scrollWheel: true, // If set to false disables the scrolling on the map.
draggable: true, // If set to false , you cannot move the map around.
};
map = new google.maps.Map( element, mapOptions ); // Till this like of code it loads up the map.
marker = new google.maps.Marker({
position: mapOptions.center,
map: map,
// icon: 'http://pngimages.net/sites/default/files/google-maps-png-image-70164.png',
draggable: true
});
}
window.initMap = initMap;
then call the map-search id in your render function
<div id="map-canvas" style={{height:500px, width:800px}}></div>

google-map-react not loading

My Google Map gives following error:
"Oops! Something went wrong. This page didn't load Google Maps correctly. See the JavaScript console for technical details."
I use Gatsby and google-map-react package. My code:
const AnyReactComponent = ({ text }) => <div>{text}</div>;
static defaultProps = {
center: {
lat: 59.95,
lng: 30.33
},
zoom: 11
};
<div style={{ height: '50vh', width: '100%' }}>
<GoogleMapReact
bootstrapURLKeys={{ key: "https://maps.google.com/maps?q=manhatan&t=&z=13&ie=UTF8&iwloc=&output=embed" }}
defaultCenter={this.props.center}
defaultZoom={this.props.zoom}
>
<AnyReactComponent
lat={59.955413}
lng={30.337844}
text="My Marker"
/>
</GoogleMapReact>
</div>
In bootstrapURLKeys you have to add google map api key not url.
you can get key from google console https://developers.google.com/maps/documentation/javascript/get-api-key
<GoogleMapReact
bootstrapURLKeys={{ key: /* YOUR KEY HERE */ }}
......
/>

React Native Maps: What's the best way to implement a draggable marker?

I have a map in which I need to add a draggable marker to allow the user to pick a point.
If I choose the conventional method of
<MapView
initialRegion={{
....
}}>
<Marker coordinate={this.state.coordinates} draggable />
</MapView
It's not a very smooth feedback for the user, since the marker first needs to be long-pressed before being draggable, and also it cannot be dragged beyond the current boundaries of the map, i.e. the user needs to manually scroll the map to a different region before being able to place the marker there.
So I found a workaround by following this concept:
https://alizahid.dev/blog/keep-marker-in-center-and-move-map-around-it
<MapView
initialRegion={{
latitudeDelta: 0.02,
longitudeDelta: 0.02,
latitude: this.state.coordinates.latitude,
longitude: this.state.coordinates.longitude
}}
onRegionChange={(result) => this.setState({coordinates: result})}
style={{height: 300}}
>
<Marker coordinate={this.state.coordinates} />
</MapView>
This works almost perfect, except for the fact I'm using a separate function using Geolocation service to get the user's current location and place the marker there
componentDidMount() {
Geolocation.getCurrentPosition((position) => {
this.setState({
coordinates: {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
});
},
(error) => {
console.log(error);
alert("Couldn't get GPS location. Please try again or choose pickup point manually.");
},
{ enableHighAccuracy: true, maximumAge: 10000, timeout: 10000, showLocationDialog: true, forceRequestLocation: true})
}
When this function returns the location, the marker is moved to the correct point, BUT, the map does not scroll to the region where the marker is placed, since initialRegion does not change the region after mounting.
If I use region instead of initialRegion, the map does not scroll at all, since the onRegionChange callback is changing the state continuously and probably conflicting with the region prop.
What could be the best workaround against all the issues?
The best way is to show a marker in centre of screen by positioning it absolute.Like this
<View style={styles.markerFixed}>
<Icon
style={{
color: '#B11C01',
}}
size={30}
name={'map-marker-alt'}
solid
/>
</View>
markerFixed: {
left: 0,
right: 0,
marginLeft: 0,
marginTop: 0,
position: 'absolute',
top: '40%',
alignItems: 'center',
},
Now you can drag your map to any location.Which will show effect like marker is moving.But map is moving in actual.Now use onRegionChangeComplete function to convert updated latlang to address.And you can show that converted address above the marker like in shot.
import Geocoder from 'react-native-geocoding';
<MapView
style={styles.mapStyle}
provider={PROVIDER_GOOGLE}
region={{
latitude: lat,
longitude: long,
latitudeDelta: 0.0922 / 10,
longitudeDelta: 0.0421 / 10,
}}
onRegionChangeComplete={this.onRegionChange}
/>
convertToAddress() {
let {lat, long} = this.state;
if (this.state.firstIndication === 0) {
this.setState({firstIndication: 1});
return;
}
Geocoder.from(lat, long)
.then(json => {
var addressComponent = json.results[0].address_components[0];
this.setState({name: addressComponent.long_name});
})
.catch(error => console.warn(error));
}[![enter image description here][1]][1]
The best workaround would be using react-native-location-view
It provides you a draggable map and you can easily get the location whatever you choose by the marker.
You can refer https://www.npmjs.com/package/react-native-location-view

onUserLocationChange changes React Native Maps region

I'm using MapView from 'react-native-maps'
I can't get the "showsMyLocationButton" to show, so I'm implementing my own.
I want do this without using React Native's geolocation because I find it to be slower than react-native-maps prop showsUserLocation. I use onUserLocationChange event which returns the coordinates. However when firing the onUserLocationChange event and setting a state which contains the userLocation, it automatically updates the region without me explicitly asking for it.
This is my code:
display_my_location(coordinate){
alert("region changed")
this.setState({
region: {
latitude: coordinate.latitude,
longitude: coordinate.longitude,
latitudeDelta: 0.004,
longitudeDelta: 0.004
},
});
}
setUserLocation(coordinate){
//alert("User location changed MAP SHOULDNT MOVE")
this.setState({
userLocation: {
latitude: coordinate.latitude,
longitude: coordinate.longitude,
latitudeDelta: 0.004,
longitudeDelta: 0.004
}
})
}
<MapView
style={styles.map}
showsMyLocationButton={true}
onUserLocationChange={locationChangedResult => this.setUserLocation(locationChangedResult.nativeEvent.coordinate)}
initialRegion={this.state.region_amon}
showsUserLocation={true}
region={this.state.region}
mapType={this.state.map_style}
showsCompass = {true}
showsMyLocationButton={true}
chacheEnabled={false}
zoomEnabled={true}
I believe you can fix this by deleting the region prop from the MapView altogether. If you need to have the map's bounding box change programmatically you can attach a ref to the map and update in componentDidUpdate using the appropriate MapView method here:
https://github.com/react-community/react-native-maps/blob/master/docs/mapview.md#methods
I have a workaround for the above issue, we can have a custom icon on the map. After clicking on the custom icon trigger a method. In the method get the current location coordinates using Geolocation and fire animateToRegion and pass the coordinates.
Step 1: Declare mapRef
const mapRef = useRef(null);
Step 2: Assing mapRef to MapView
<View style={{flex: 1}>
<MapView
ref={mapRef}
...........
/>
<TouchableOpacity
onPress={currentLocationHandler}>
<MaterialIcons
name="my-location"
size={24}
color="black"
/>
</TouchableOpacity>
</View>
Step 3: currentLocationHandler method
const currentLocationHandler = () => {
<!-- Get location coordinates using GeoLocation npm package -->
let currentRegion = {
latitude: latitude from geolocation,
longitude: longitude from geolocation,
latitudeDelta: 0.001,
longitudeDelta: 0.001,
};
mapRef.current.animateToRegion(currentRegion, 3 * 1000);
}
I hope the above steps help you to solve the issue

marker react native map can't drag

i' ve using react-native-map air bnb to render a google map in my native app.
The map and marker is showed up but the marker can't drag.
this is my script
<View style={Style.mapContainer}>
<GeoLocation onSetInitalPos={this.onSetInitialPosition}
onSetLastPos={this.onSetLastPosition}/>
<MapView style={Style.map} region={this.state.region} onRegionChange={this.onRegionChange}>
<MapView.Marker draggable={this.state.draggable}
coordinate={this.state.marker.latlng}
title={this.state.marker.title}
description={this.state.marker.description}
onDrag={() => console.log('onDrag')}
/>
</MapView>
<AutoCompleteMap onSetNewPlace={this.setMarkerPosition}/>
</View>
According to docs of react-native-maps draggable:
This is a non-value based prop. Adding this allows the marker to be draggable (re-positioned).
Instead of draggable={this.state.draggable}, you should be defining it like this
<MapView style={Style.map} region={this.state.region} onRegionChange={this.onRegionChange}>
<MapView.Marker
draggable
coordinate={this.state.marker.latlng}
title={this.state.marker.title}
description={this.state.marker.description}
onDragEnd={this.onUserPinDragEnd.bind(this)} />
</MapView>
Here's a snippet of working draggable marker version of my project. Nothing fancy, just using Exponent Components to import MapView, instead of npm installing and linking.
<Components.MapView
ref={(map) => this.map = map}
style={{width: Metrics.screenWidth, height: mapHeight, zIndex: 0}}
region={{
latitude: this.state.location.coords.latitude,
longitude: this.state.location.coords.longitude,
latitudeDelta: 0.0100,
longitudeDelta: 0.0100,
}}
>
<Components.MapView.Marker
key={'i29'}
draggable
onDragEnd={this.onUserPinDragEnd.bind(this)}
title={'You are here'}
coordinate={{
latitude: this.state.userLocation.coords.latitude,
longitude: this.state.userLocation.coords.longitude,
}}
/>
</Components.MapView>
And just to be sure, have you tried hold pressing the marker to drag it? It's kinda slow.

Categories