ReactJS props updating at different speeds in same component - google-maps

I have a Google maps component in a React/Redux app. When you click an item from a list, it passes down an array of coordinates to render as directions from the user's current location. The props are being passed fine through react-redux mapStateToProps. I'm calling a function to generate the the polyline, this is where my problem is. The marker is generated fine inside of render, but the directions do not render until another entry is clicked. Basically it's always one step behind the current markers. So, for 2 stops, I'll have directions from current location to stop 1, but not stop 2. For 3 stops, current location to stop 1 to stop 2 will be generated, but not stop 3.
When I log out the length of the array of stops inside of render I get the expected amount, a length of 1 for 1 stop. I have tried putting the method inside of componentWillWillReceiveProps and componentWillUpdate, and both methods will log a 0 for 1 stop.
Here's the component, if relevant:
const GoogleMapComponent = React.createClass({
mixin: [PureRenderMixin],
getInitialState: function() {
return {
map: null,
maps: null,
color: 0
}
},
componentWillUpdate: function() {
console.log('LOGS ZERO HERE', this.props.tourList.length)
if (this.state.maps) {
this.calculateAndDisplayRoute(this.state.directionsService, this.state.directionsDisplay, this.props.tourList);
}
},
saveMapReferences: function(map, maps) {
let directionsDisplay = new maps.DirectionsRenderer({map, polylineOptions: {strokeColor: '#76FF03'}, suppressMarkers: true});
let directionsService = new maps.DirectionsService();
this.setState({ map, maps, directionsService, directionsDisplay });
},
generateWaypoints: function(coords) {
return coords.map((coord) => {
return { location: new this.state.maps.LatLng(coord.lat, coord.lng) };
});
},
calculateAndDisplayRoute: function(directionsService, directionsDisplay, tourStops) {
let origin = this.props.userLocation || { lat: 37.77, lng: -122.447 };
let destination = tourStops[tourStops.length - 1];
let directions = { origin, destination, travelMode: this.state.maps.TravelMode.DRIVING };
if (this.props.tourList.length > 1) {
directions.waypoints = this.generateWaypoints(tourStops);
}
if (tourStops.length > 0) {
directionsService.route(directions, (response, status) => {
if (status === this.state.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
console.log('Directions request failed due to ' + status);
}
});
} else {
directionsDisplay.set('directions', null);
}
},
render: function() {
console.log('LOGS 1 HERE', this.props.tourList.length)
let markers = this.props.tourList.map((marker, idx) => {
let loc = marker.prevLoc ? marker.prevLoc : 'your current location.';
return <Marker className='point' key={idx} image={marker.poster} lat={marker.lat} lng={marker.lng} location={marker.location} price={marker.price} loc={loc} />
});
let defaultCenter = {lat: 37.762, lng: -122.4394};
let defaultZoom = 12
if (this.props.userLocation !== null) {
return (
<div className='map'>
<GoogleMap defaultCenter={defaultCenter} defaultZoom={defaultZoom} yesIWantToUseGoogleMapApiInternals={true}
onGoogleApiLoaded={({map, maps}) => {
map.setOptions({styles: mapStyles});
this.saveMapReferences(map, maps);
}} >
{markers}
<UserMarker lat={this.props.userLocation.lat} lng= {this.props.userLocation.lng} />
</GoogleMap>
</div>
);
}
return (
<div className='map'>
<GoogleMap defaultCenter={defaultCenter} defaultZoom={defaultZoom} yesIWantToUseGoogleMapApiInternals={true}
onGoogleApiLoaded={({map, maps}) => {
map.setOptions({styles: mapStyles});
this.saveMapReferences(map, maps);
}} >
{markers}
</GoogleMap>
</div>
);
}
});
function mapStateToProps(state) {
return {
tourList: state.sidebar.tourList,
userLocation: state.home.userLocation
}
}
export default connect(mapStateToProps)(GoogleMapComponent);

Figured it out, I was not passing nextProps to componentWillUpdate, so the function was always being called with the old props.

componentWillUpdate is called prior to this.props being updated. Change componentWillUpdate as follows:
componentWillUpdate: function(nextProps) {
console.log('SHOULD LOG ONE HERE', nextProps.tourList.length)
if (this.state.maps) {
this.calculateAndDisplayRoute(this.state.directionsService, this.state.directionsDisplay, nextProps.tourList);
}
}

Related

VueJS Child component GMAP not rerender when parent data updates

Hi I'm new with Vue and I bump to this problem where when I update the location it doesn't reflect on the child component. I've used computed and watch but still not updating. forgive me as I don't have a strong knowledge about VueJS.
so in my code I have location(computed) which listen to localLocation(data) that is bind to the project.location. I update the location using the method setPlace()
hope anyone can help. here's my code below:
<template lang="pug">
.google-maps-wrapper
template(v-if="!location")
f7-list.no-margin-top
f7-list-button(title='Add Location' #click="isAutocompleteOpen = true")
template(v-if="location")
f7-list.no-margin(inline-labels no-hairlines-md)
f7-list-item.short-text Address: {{ location.formattedAddress }}
div
gmap-map.main-map(ref="googleMap" :options="mapOptions" :center="location.position" :zoom="16" :map-type-id="mapTypeId")
gmap-marker(:position="location.position" :clickable="false")
f7-actions(ref='mapsAction')
f7-actions-group
f7-actions-group
f7-actions-button(#click="copyToClipboard()") Copy to Clipboard
f7-actions-button(#click="isAutocompleteOpen = true") Change Address
f7-actions-button(v-if="$root.$device.ios || $root.$device.macos" #click="$refs.navigateActions.f7Actions.open()") Navigate
f7-actions-button(v-else #click="googleMapsNavigate()") Navigate
f7-actions-group
f7-actions-button
b Cancel
f7-actions(ref='navigateActions')
f7-actions-group
f7-actions-group
f7-actions-button(#click="googleMapsNavigate()") Google Maps
f7-actions-button(#click="appleMapsNavigation()") Apple Maps
f7-actions-group
f7-actions-button
b Cancel
f7-popup.locate-project(:opened='isAutocompleteOpen' #popup:closed='closeAutocomplete()')
f7-page
f7-navbar
f7-nav-title Search Location
f7-nav-right
f7-link(#click="closeAutocomplete()") Close
f7-searchbar.searchbar(search-container=".search-list" search-in=".item-title" #input="searchLocation($event)" placeholder="Enter Location" clear-button)
f7-list.not-found(v-if="!pendingSearch && !suggestedLocations.length && searchedLocation")
f7-list-item(title="Nothing found")
f7-block-title.gmap-preloader(v-if="pendingSearch")
f7-preloader(size="16")
f7-list.search-list.searchbar-found.gmap-search-list(v-if="!pendingSearch && suggestedLocations.length" media-list)
f7-list-item.item-button(v-for='(location, index) in suggestedLocations' :title="location.structured_formatting.main_text" :subtitle="location.structured_formatting.secondary_text" #click="updateLocation(location)")
</template>
<script>
import { debounce } from 'lodash-es'
import { Plugins } from '#capacitor/core'
const { Clipboard } = Plugins
const { Browser } = Plugins
const debounceSearch = debounce(run => {
run()
}, 500)
import defaultMixin from '#/mixins/default'
import {
f7Actions,
f7ActionsLabel,
f7ActionsGroup,
f7ActionsButton,
f7Popup,
f7Page,
f7NavRight,
f7NavTitle,
f7Navbar,
f7Block,
f7BlockTitle,
f7Label,
f7Link,
f7Preloader,
f7List,
f7ListButton,
f7ListItem,
f7ListInput,
f7Icon,
f7Searchbar
} from 'framework7-vue'
import { gmapApi } from 'vue2-google-maps'
export default {
name: "google-maps",
mixins: [defaultMixin],
props: ['project'],
components: {
f7Actions,
f7ActionsLabel,
f7ActionsGroup,
f7ActionsButton,
f7Popup,
f7Page,
f7NavRight,
f7NavTitle,
f7Navbar,
f7Block,
f7BlockTitle,
f7Label,
f7Link,
f7Preloader,
f7List,
f7ListButton,
f7ListItem,
f7ListInput,
f7Icon,
f7Searchbar
},
data() {
return {
mapTypeId: "terrain",
directionsService: undefined,
directionsDisplay: undefined,
autocompleteService: undefined,
autocompleteRequest: undefined,
navigate: false,
localLocation: this.project.location,
mapOptions: {
disableDefaultUI: true,
backgroundColor: '#d3d3d3',
draggable: false,
zoomControl: false,
fullscreenControl: false,
streetViewControl: false,
clickableIcons: false
},
isAutocompleteOpen: false,
suggestedLocations: [],
pendingSearch: false,
origin: '',
searchedLocation: ''
}
},
computed: {
location() {
return this.localLocation
},
google: gmapApi
},
methods: {
appleMapsNavigation(){
window.open(`http://maps.apple.com/?daddr=${encodeURI(this.project.location.formattedAddress)}`)
},
googleMapsNavigate(){
if(this.$root.$device.ios){
window.open(`comgooglemaps://?daddr=${encodeURI(this.project.location.formattedAddress)}`)
}else{
window.open(`https://www.google.com/maps/dir//${encodeURI(this.project.location.formattedAddress)}`)
}
},
closeAutocomplete() {
this.isAutocompleteOpen = false
this.searchedLocation = ''
this.suggestedLocations = []
this.$f7.searchbar.clear('.searchbar')
},
updateLocation( location ){
this.getGeocode(location.place_id, output => {
this.suggestedLocations = []
this.setPlace(output[0])
})
},
getGeocode( placeId, callback ){
const geocoder = new google.maps.Geocoder()
this.$f7.dialog.preloader()
geocoder.geocode({placeId}, output => {
callback(output)
this.closeAutocomplete()
this.$f7.dialog.close()
})
},
searchLocation( event ) {
this.pendingSearch = true
this.searchedLocation = event.target.value
debounceSearch(() => {
if(!this.searchedLocation) {
this.pendingSearch = false
this.suggestedLocations = []
return
}
const autocompleteService = new google.maps.places.AutocompleteService()
autocompleteService.getPlacePredictions({input: this.searchedLocation}, output => {
if(this.pendingSearch){
this.suggestedLocations = output || []
this.pendingSearch = false
}
})
})
},
setPlace( selectedLocation ) {
if(!selectedLocation.formatted_address) return;
const data = {
location: {
formattedAddress: selectedLocation.formatted_address,
position: {
lat: selectedLocation.geometry.location.lat(),
lng: selectedLocation.geometry.location.lng()
}
}
};
this.$f7.popup.close('.add-location')
if(this.$refs.autocomplete) this.$refs.autocomplete.$el.disabled = true
this.localLocation = data.location
db.collection("projects")
.doc(this.project.id)
.set(data, {
merge: true
})
.then()
},
copyToClipboard() {
Clipboard.write({
string: this.project.location.formattedAddress
});
}
}
}
</script>
Code Summary (just the summary of the whole code above)
Template that displays the address and map
.google-maps-wrapper
template(v-if="!location")
f7-list.no-margin-top
f7-list-button(title='Add Location' #click="isAutocompleteOpen = true")
template(v-if="location")
f7-list.no-margin(inline-labels no-hairlines-md)
f7-list-item.short-text Address: {{ location.formattedAddress }}
div
gmap-map.main-map(ref="googleMap" :options="mapOptions" :center="location.position" :zoom="16" :map-type-id="mapTypeId")
gmap-marker(:position="location.position" :clickable="false")
Last line of the template where it updates the location
f7-list-item.item-button(v-for='(location, index) in suggestedLocations' :title="location.structured_formatting.main_text" :subtitle="location.structured_formatting.secondary_text" #click="updateLocation(location)")
Script that updates the location
updateLocation( location ){
this.getGeocode(location.place_id, output => {
this.suggestedLocations = []
this.setPlace(output[0])
})
},
setPlace( selectedLocation ) {
if(!selectedLocation.formatted_address) return;
const data = {
location: {
formattedAddress: selectedLocation.formatted_address,
position: {
lat: selectedLocation.geometry.location.lat(),
lng: selectedLocation.geometry.location.lng()
}
}
};
this.$f7.popup.close('.add-location')
if(this.$refs.autocomplete) this.$refs.autocomplete.$el.disabled = true
this.localLocation = data.location
db.collection("projects")
.doc(this.project.id)
.set(data, {
merge: true
})
.then()
},
Initial Page No Address yet
Actual Output after adding location
Expected Output

Hover-Enabled Sub Context Menu in Viewer

Question: How do I modify the below code so that (i) upon hovering over a menu item in the context menu, the correpsonding submenu appears, and (ii) the menu(s) disappear after clicking on a menu item?
Context: Currently, when you press the menu item corresponding with the sub-menu, the original context menu stays fixed (i.e. when clicking on empty space in the viewer, the menu remains and appears fully interactive). When you press on the same menu item for a second time, it opens the sub-menu, but similar to the original menu, this sub-menu also remains fixed when we press one of its menu items.
For reference, I've included some screenshots of the current context menu and sub-menu.
The corresponding code is as follows:
...
function ContextMenu(viewer, options) {
Autodesk.Viewing.Extensions.ViewerObjectContextMenu.call(this, viewer, options);
}
ContextMenu.prototype = Object.create(Autodesk.Viewing.Extensions.ViewerObjectContextMenu.prototype);
ContextMenu.prototype.constructor = ContextMenu;
ContextMenu.prototype.buildMenu = function(event, context) {
if (contextMenuState.disabled) {
return null;
}
// Context is a true false flag used internally by autodesk to determine which type of menu to build.
// If false, it has the side effect of selecting the right-clicked element.
var autodeskMenu = Autodesk.Viewing.Extensions.ViewerObjectContextMenu.prototype.buildMenu.call(this, event, context);
const filterOut = ['Hide Selected', 'Clear Selection', 'Show All Objects'];
const menu = autodeskMenu.filter(m => !filterOut.includes(m.title));
menu.push({
title: "Custom 1",
target: function() {
doSomeCustom1Stuff();
}
});
menu.push({
this.custom2ItemGenerator(<parameter1>, <parameter2>, <parameter3>, <parameter4>);
});
return menu;
};
ContextMenu.prototype.custom2ItemGenerator = function(p1, p2, p3, p4) {
return {
title: "< Custom 2",
target: [
{
title: "Sub-custom 1",
target: function() {
...doSomething1(p1);
}
},
{
title: "Sub-custom 2",
target: function() {
...doSomething2(p2);
}
},
{
title: "Sub-custom 3",
target: function() {
...doSomething3(p3);
}
},
{
title: "Sub-custom 4",
target: function() {
...doSomething4(p4);
}
},
{
title: "Sub-custom 5",
target: function() {
...doSomething5(p5);
}
}
]
}
};
/* Not sure the following to overrides ('hide' and 'addCallbackToMenuItem') are correct, or even necessary.
ContextMenu.prototype.hide = function() {
if (this.open) {
this.menus = [];
this.open = false;
this.container.removeEventListener('touchend', this.OnHide);
this.container.removeEventListener('click', this.OnHide);
this.container.removeEventListener(<Custom Name>, this.OnMove); // same Custom Name as 1st parameter function below -- Autodesk.Viewing.theExtensionManager.registerExtension
this.container.parentNode.removeChild(this.container);
this.container = null;
return true;
}
return false;
};
ContextMenu.prototype.addCallbackToMenuItem = function (menuItem, target) {
var that = this;
if (target.constructor == Array) {
menuItem.addEventListener('click', function (event) {
that.hide();
target();
event.preventDefault();
return false;
}, false);
} else {
menuItem.addEventListener('mouseover', function (event) {
that.hide();
target();
event.preventDefault();
return false;
}, false);
}
};
function ContextMenuLoader(viewer, options) {
Autodesk.Viewing.Extension.call(this, viewer, options);
this.load = function() {
viewer.setContextMenu(new ContextMenu(viewer, options));
return true;
};
this.unload = function() {
viewer.setContextMenu(new Autodesk.Viewing.Extensions.ViewerObjectContextMenu(viewer, options));
return true;
};
}
ContextMenuLoader.prototype = Object.create(Autodesk.Viewing.Extension.prototype);
ContextMenuLoader.prototype.constructor = ContextMenuLoader;
Autodesk.Viewing.theExtensionManager.registerExtension(<Custom Name>, ContextMenuLoader);
....
Sorry about this problem, we're investigating this. Our tracking code is LMV-3740

React Native Map (Airbnb) + Markers animation

I want to animate the React-native-maps {Google} markers.
I tried with the animated module, but the markers do not allow complex styles.
Is there any function to modify the coordinates of the marker and give it animation?, like a:
marker.setAnimation(google.maps.Animation.BOUNCE);
I have tried with:
<MapView.Marker.Animated>
But I can not create the effect. Is there a function that edits the coordinates as an animation drop?
React native map marker is by default "not animated", it can not accept gif images, sprites, animation api and so on . . However, I was able to animate it the tough way through image transition. Here is my example:
constructor(props, context) {
super(props, context);
this.state = {
startTransition: 1,
endTransition: 4,
};
}
componentDidMount() {
this.animate();
}
animate() {
const {startTransition, endTransition} = this.state;
if(startTransition < endTransition){
let currentTransition = startTransition + 1;
this.setState({startTransition: currentTransition});
} else {
this.setState({startTransition: 1});
}
let x = setTimeout(()=>{
this.animate()
}, 500);
}
renderImg(imgTrans) {
if(imgTrans === 1) {
return require('./walk1.png');
}
if(imgTrans === 2) {
return require('./walk2.png');
}
if(imgTrans === 3) {
return require('./walk3.png');
}
if(imgTrans === 4) {
return require('./walk4.png');
}
}
render() {
const {startTransition} = this.state;
return (
<MapView.Marker
coordinate={tapCoords}
image={this.renderImg(startTransition)}
>
)
}
This is how I did the animation for now.

How to restrict Google Maps search results to only one country properly?

I am developing an application, in Ionic, where you can plan a trip with a start address and and end address. However I want to limit this feature to only one country. Before writing I have been searching for solutions on the internet, but none of them worked for me.
Have tried these suggestions:
https://stackoverflow.com/a/8282093/8130808
https://stackoverflow.com/a/10170421/8130808
Here is how I have tried to approach it:
//Places markers and displays a route, so the user can accept the current placing
newRoutePlaceMarks(place: any): void {
var googleDiplay = new google.maps.DirectionsRenderer({ draggable: true });
var route = this.directionsDisplay;
//A bit of a hack, sadly Typescript and google maps arent the best of buddies
this.directionsService.route({
origin: this.routeStart,
destination: this.routeEnd,
travelMode: 'DRIVING',
}, function (response, status) {
if (status === 'OK') {
console.log("status is OK trying to put directions up");
//The reason why I've set the addListener before the actual route is so it gets triggered
//on the creation of the route. Had some problem with figuring out how to actually handle
//the data when on the route creation, as this response function is in strict mode, and outside
google.maps.event.addListener(route, "directions_changed", function () {
console.log("Route changed");
this.global = ShareService.getInstance();
this.directions = route.getDirections();
this.metersToDist = this.directions.routes[0].legs[0].distance.value;
this.timeToDist = this.directions.routes[0].legs[0].duration.value;
this.startAddress = this.directions.routes[0].legs[0].start_address;
this.startCord = this.directions.routes[0].legs[0].start_location;
this.endAddress = this.directions.routes[0].legs[0].end_address;
this.endCord = this.directions.routes[0].legs[0].end_location;
this.global.setMetersToDist(this.metersToDist);
this.global.setTimeToDist(this.timeToDist);
this.global.setStartAddress(this.startAddress);
this.global.setStartCord(this.startCord);
this.global.setEndAddress(this.endAddress);
this.global.setEndCord(this.endCord);
var options = {
types: ['geocode'],
componentRestrictions: { country: "dk" }
};
google.maps.places.Autocomplete(this.startAddress, options);
});
//The actual initialiser for the route
route.setDirections(response);
} else {
alert('Could not display route ' + status);
}
});
}
My problem is that the input is HTTPELEMENT, I get the input from an alert dialog
newRouteInput() {
let alert = this.alertCtrl.create({
title: 'New route',
inputs: [
{
name: 'routeStart',
placeholder: 'Start of route'
},
{
name: 'routeEnd',
placeholder: 'End of route'
}
],
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: data => {
console.log('Cancel clicked');
}
},
{
text: 'Debug start and end',
handler: data => {
if (data.username !== "undefined") {
console.log(data.routeStart + " " + data.routeEnd);
this.routeStart = "Brøndby Strand";
this.routeEnd = "Hvidovre";
this.newRoutePlaceMarks(this.map);
this.routeButton = false;
} else {
return false;
}
}
},
{
text: 'Place route markers',
handler: data => {
if (data.username !== "undefined") {
this.routeStart = data.routeStart;
this.routeEnd = data.routeEnd;
this.newRoutePlaceMarks(this.map);
this.routeButton = false;
} else {
console.log(data.routeStart + " " + data.routeEnd);
return false;
}
}
}
]
});
alert.present();
}
When I run this I get an error because of this.startAddress. It's not null, it contains the start address:
InvalidValueError: not an instance of HTMLInputElement

React Google Maps module - How to handle GeoJSON MultiPolygons

So I've been using the google-maps-react example for converting GeoJSON data to polygons. The problem I've run into is that the example doesn't support converting GeoJSON features of the 'MultiPolygon' type. (Multiple polygons grouped together).
Is there anything I could change in the example to support that? Thinking I might be able to just add a case to the following function:
function geometryToComponentWithLatLng(geometry) {
const typeFromThis = Array.isArray(geometry);
const type = typeFromThis ? this.type : geometry.type;
let coordinates = typeFromThis ? geometry : geometry.coordinates;
switch (type) {
case 'Polygon':
return {
ElementClass: Polygon,
paths: coordinates.map(
geometryToComponentWithLatLng, {
type: 'LineString'
}
)[0],
};
case 'LineString':
coordinates = coordinates.map(
geometryToComponentWithLatLng, {
type: 'Point'
}
);
return typeFromThis ? coordinates : {
ElementClass: Polyline,
path: coordinates,
};
case 'Point':
coordinates = {
lat: coordinates[1],
lng: coordinates[0]
}
return typeFromThis ? coordinates : {
ElementClass: Marker,
ChildElementClass: InfoWindow,
position: coordinates,
};
default:
throw new TypeError('Unknown geometry type: ${ type }');
}
}
Managed to fix this one myself by adding a case to the switch for 'MultiPolygon', and making some slight changes to the case for 'Polygon', like so:
switch (type) {
case 'MultiPolygon':
return {
ElementClass: Polygon,
paths: coordinates.map(
geometryToComponentWithLatLng, {
type: 'Polygon'
}
),
};
case 'Polygon':
coordinates = coordinates.map(
geometryToComponentWithLatLng, {
type: 'LineString'
}
)[0];
return typeFromThis ? coordinates : {
ElementClass: Polygon,
path: coordinates,
};
case 'LineString':
coordinates = coordinates.map(
geometryToComponentWithLatLng, {
type: 'Point'
}
);
return typeFromThis ? coordinates : {
ElementClass: Polyline,
path: coordinates,
};
case 'Point':
coordinates = {
lat: coordinates[1],
lng: coordinates[0]
}
return typeFromThis ? coordinates : {
ElementClass: Marker,
ChildElementClass: InfoWindow,
position: coordinates,
};
default:
throw new TypeError('Unknown geometry type: ${ type }');
}