Access data fields outside of export default - Vue - javascript

I was wondering if it is possible to access the data that is within the export default in my javascript file for my Vue component. I am trying to get the contents of the routes array inside the calculateAndDisplayRoute() function.
overview.js
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var origin, dest;
for (var route in this.routes /*<--HERE*/) {
console.log('www')
if(route.id == this.filter){
console.log('true')
}
}
directionsService.route({
origin: 'Vancouver',
destination: 'Chicago',
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
export default {
name: 'fleet-overview',
data () {
return {
view: '',
routes: [], //<--HERE
users: [],
errorRoute: '',
response: [],
filter: 'searchby',
searchTerm: '',
users: [],
}
},
created: function () {
this.routeView();
},
methods: {
initMap: function(){
this.$nextTick(function(){
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 45.49, lng: -73.61},
zoom: 9
});
directionsDisplay.setMap(map);
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
document.getElementById('filterselect').addEventListener('change', onChangeHandler);
})
}
//...
}

You could use call to set the context (this) appropriately.
calculateAndDisplayRoute.call(this, directionsService, directionsDisplay);
Or you could rework the function definition to accept a context (you can't call it this, but you could call it context).
function calculateAndDisplayRoute(context, directionsService, directionsDisplay) {
...
for (var route in context.routes /*<--HERE*/) {
console.log('www')
if(route.id == context.filter){
console.log('true')
}
}
...
}
Then in your initMap, you would pass this as the first argument:
calculateAndDisplayRoute(this, directionsService, directionsDisplay);

Related

Map: Expected mapDiv of type Element but was passed undefined - google maps

I have a map inside a div with a reference #mapa
When i want to trace a route in the map the map refreshes. I want to not refresh the map i have the following code:
<div style="height: 500px; width: auto;" #mapa>
<google-map height="500px" width="100%" [zoom]="zoom" [center]="center" [options]="options" (mapClick)="click($event)">
<map-marker #markerElem *ngFor="let marker of markers" [position]="marker.position" [label]="marker.label" [title]="marker.title" [options]="marker.options" (mapClick)="openInfo(markerElem, marker.info)" (mapDragend)="moveMap($event)">
</map-marker>
<map-info-window>{{ infoContent }}</map-info-window>
</google-map>
</div>
If i remove the div with the reference #mapa and i put it the reference into the <google-map> tag i got the title error and show the map without routes.
trazarRutaMapa() {
const directionsService = new google.maps.DirectionsService;
const directionsDisplay = new google.maps.DirectionsRenderer;
const map = new google.maps.Map(this.mapa.nativeElement, {
zoom: 7,
center: {
lat: this.markers[0].position.lat,
lng: this.markers[0].position.lng
}
});
directionsDisplay.setMap(map);
directionsDisplay.setOptions({
suppressMarkers: false,
draggable: true,
markerOptions: {
icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
}
});
directionsService.route({
origin: {
lat: this.markers[0].position.lat,
lng: this.markers[0].position.lng
},
destination: {
lat: this.markers[1].position.lat,
lng: this.markers[1].position.lng
},
travelMode: google.maps.TravelMode.DRIVING,
}, (response, status) => {
if (status === google.maps.DirectionsStatus.OK) {
console.log('ESTATUS OKEY');
directionsDisplay.setDirections(response);
} else {
window.alert("Fallo el estatus" + status);
}
});
}
As far as I can see you can accomplish your goal just using the #angular/google-maps official module.
Your HTML will become something like this
<google-map [options]="options">
<map-marker *ngFor="let some of somearray" [icon]="...", [label]="...", [position]="..."></map-marker>
<map-directions-renderer [directions]="..." [options]="..."></map-directions-renderer>
</google-map>
and your trazarRoutaMapa() method will become something like this:
trazarRoutaMapa(): void {
const directionsService = new google.maps.DirectionsService; // better if injected from constructor
const request: google.maps.DirectionsRequest = {
destination: {
lat: this.markers[0].position.lat,
lng: this.markers[0].position.lng
},
origin: {
lat: this.markers[1].position.lat,
lng: this.markers[1].position.lng
},
travelMode: google.maps.TravelMode.DRIVING
};
return directionsService.route(
request,
(response, status) => {
if (status === google.maps.DirectionsStatus.OK) {
console.log('ESTATUS OKEY');
directionsDisplay.setDirections(response);
} else {
window.alert("Fallo el estatus" + status);
}
});
}
Disclaimer: I didn't test the code, just created on notepad copy/pasting :)

Handling Google Geocode Callback Results to Vue JS Model

Here's my issue... I have two selections for my user, use current location, or use a zip code. When the user selects a zip code I make a call to the Google geocode API and retrieve the central point for that zip code. I want to be able to put these coordinates into my Vue model and then execute a method within Vue called refresh which retrieves some data from my database and calls a function that sets up the map with markers and bounds. Since the callback function is decoupled from the model, I cannot seem to set the Vue properties, nor can I call the method. How do I handle the callback?
Please note that the refresh method works properly when using the selection for current location.
getLocation is called when the user selects "Current Location"
checkZip is called when the user selects "Use Zip Code"
<script>
var app = new Vue({
el: '#app-content',
data: {
locationType: "CurrentLocation",
lat: "",
lng: "",
radiusInMiles: 10,
filters: [],
zipCode: "",
geoError: "",
error: "",
results: []
},
methods: {
getLocation: function () {
this.zipCode = "";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.storeLocation, this.locationError);
} else {
this.locationType = "ZipLocation";
console.log("Geolocation does not appear to be supported by the browser.");
this.geoError = "Unable to obtain location. Please make sure location services are turned on and try again.";
}
},
storeLocation: function (position) {
this.lat = position.coords.latitude;
this.lng = position.coords.longitude;
this.refresh();
},
locationError: function (err) {
this.locationType = "ZipLocation";
this.results = [];
console.warn(err);
this.geoError = "Unable to obtain location. Please make sure location services are turned on and try again.";
},
refresh: function () {
if (!(this.lat && this.lng && this.radiusInMiles && this.filters)) {
console.log("Location and filters are undefined.");
}
else {
//https://github.com/axios/axios
axios
.post('xyxyxyxyx', {
lat: this.lat,
lng: this.lng,
radiusInMiles: this.radiusInMiles,
filters: this.filters.toString()
})
.then(response => {
this.results = response.data.d;
//Send to map function...
loadMap(this.lat, this.lng, this.results);
})
.catch (error => console.log(error))
}
},
checkZip: function () {
if (this.zipCode.length == 5 && !isNaN(this.zipCode)) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': 'zipcode ' + this.zipCode }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//Here's my issue...
//How do I store to the model and then call this.refresh
this.lat = results[0].geometry.location.lat();
this.lng = results[0].geometry.location.lng();
this.refresh();
} else {
console.error("Request failed.")
}
});
}
}
}
})
</script>
I was able to get this to work by copying the Vue model into a variable (self).
How can I update a Vue app's or component's property in a promise call back?
checkZip: function () {
if (this.zipCode.length == 5 && !isNaN(this.zipCode)) {
var self = this;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': 'zipcode ' + this.zipCode }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
self.lat = results[0].geometry.location.lat();
self.lng = results[0].geometry.location.lng();
self.refresh();
} else {
console.error("Request failed.")
}
});
}
}

How to get google handle_geolocation_query map to display directions from users location

var endlocation = {
'center': '52.5606064,2.0312582999999904',
'zoom': 10
};
var start = navigator.geolocation.getCurrentPosition(handle_geolocation_query);
var themap;
var destination = "Wednesbury, WS10 7TB";
$(document).ready(function () {
$('#map').gmap({
'center': endlocation.center,
'zoom': endlocation.zoom,
'disableDefaultUI': true,
'callback': function () {
themap = this;
$('#submit').click(function () {
themap.displayDirections({
'origin': start,
'destination': destination,
'travelMode': google.maps.DirectionsTravelMode.DRIVING,
'unitSystem': google.maps.UnitSystem.IMPERIAL
}, {
'panel': document.getElementById('directions')
},
function (response, status) {
(status === 'OK') ? $('#results').show() : $('#results').hide();
});
return false;
});
}
});
navigator.geolocation.getCurrentPosition(handle_geolocation_query);
});
function handle_geolocation_query(position) {
start = new google.maps.LatLng(lat, lon);
themap.get('map').panTo(start);
}
I cant seem to figure out what I should pass to the handle_geolocation_query to get the map
to give directions from the users location to a fixed point. Thanks in advance for any help and sorry I'm a noob to maps. Heres the html:
<div id="map" style="height:500px;"><div>
If the rest of your code works, this should do the same as the submit, but automatically when the handle_geolocation_query function is run.
function handle_geolocation_query(position) {
start = new google.maps.LatLng(lat, lon);
themap.displayDirections({
'origin': start,
'destination': destination,
'travelMode': google.maps.DirectionsTravelMode.DRIVING,
'unitSystem': google.maps.UnitSystem.IMPERIAL
}, {
'panel': document.getElementById('directions')
},
function (response, status) {
(status === 'OK') ? $('#results').show() : $('#results').hide();
});
});

Google Maps DirectionsService multiple calls

Does anyone know why this is only giving me directions for n+1 routes. For example from A-B-C-D-E-F, it will give me the following routes:
A-B
B-C (empty result)
C-D
D-E (empty result)
E-F
Here's my google maps code, and I'm calling it with (inside a UIWebView):
showDirections([A, B, C, D, E], true);
var directionsService = new google.maps.DirectionsService();
function showDirections(locations, metric) {
var units = metric ? google.maps.UnitSystem.METRIC : google.maps.UnitSystem.IMPERIAL;
for (i=0; i<locations.length-1; i++) {
console.log('navigating: '+locations[i].title+' to '+locations[i+1].title);
var request = {
origin: new google.maps.LatLng(locations[i].location.lat, locations[i].location.lng),
destination: new google.maps.LatLng(locations[i+1].location.lat, locations[i+1].location.lng),
travelMode: google.maps.DirectionsTravelMode.DRIVING,
avoidHighways: !!(locations[i].avoidHighway),
unitSystem: units
};
setTimeout(function() { getDirections(request); }, 2000);
}
window.location = 'directionsstatus://LOADED';
}
function renderDirections(directions) {
var directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setPanel(document.getElementById('panel'));
directionsDisplay.setDirections(directions);
}
function getDirections(request) {
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
renderDirections(response);
} else {
alert(status);
window.location = 'directionsstatus://' + status;
}
});
}

Detect the user current location,add a marker onto that position in Sencha Touch V2

The code below facilitates a map to be displayed with markers added onto it from data in a JSON file.The getDirections from one marker to another has also been facilitated.
Need to:Detect the user current location,add a marker onto that position and apply that location to the start variable given within the code below so that directions from that current position to the marker that has been tapped can be plotted.
Ext.define('Navigator.view.mapcard', {
extend: 'Ext.Map',
xtype: 'mapcard',
config: {
title: 'Mappa',
iconCls: 'maps',
// useCurrentLocation: true,
mapOptions: {
center: new google.maps.LatLng('24.859622', '18.84089'),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
}
},
listeners: {
maprender: function (comp, map) {
var data = Ext.getStore('Contacts'),
marker = [], infowindow = [],
dist = [];
data.on('load', function () {
data.each(function (rec, idx, cnt) {
var latLng = new google.maps.LatLng(rec.get('latitude'), rec.get('longitude'));
marker[idx] = new google.maps.Marker({
map: map,
position: latLng
}),
infowindow[idx] = new google.maps.InfoWindow({
content: rec.get('title')
});
google.maps.event.addListener(marker[idx], 'click', function () {
infowindow[idx].open(map, marker[idx]);
if (dist.length === 0) {
dist.push(rec.get('title'));
} else if (dist.length === 1) {
dist.push(rec.get('title'));
} else if (dist.length > 1) {
// need reload map
dist = [];
dist.push(rec.get('title'));
}
if (dist.length === 2) {
var start = dist[0],
end = dist[1],
request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
var directionsDisplay = new google.maps.DirectionsRenderer(),
directionsService = new google.maps.DirectionsService();
directionsDisplay.setMap(map);
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
});
//setTimeout(function () { map.panTo(latLng) }, 1000);
});
});
}
}
}
});

Categories

Resources