How to get Multiple parameter in other component in angular 2 - angular2-routing

This is a function in one ts file where I am passing latitude and longitude. Now I have to get these lat long in other component so how to get these parameter in other component.
routeWithData(id, latitude, longitude)
{
//console.log(latitude, longitude);
this.router.navigate(['/provider/bookings/'+id+'/details/map-location/'+latitude+'/'+longitude]);
}

if you navigate with router.navigate(['/someroute',{someProperty:"SomeValue"}]
Follow this:
constructor(routeParams: RouteParams){ let myPassedData: any=routeParams.params;console.log(myPassedData.someProperty); #Prints"SomeValue"}
You can get an idea of how to use it from here:
how to pass RouteData via Router.navigate in angular2

You can navigate either by passing all parameters in the URL
routeWithData(id, latitude, longitude) {
//console.log(latitude, longitude);
this.router.navigate(['/provider/bookings/'+id+'/details/map-location/'+latitude+','+longitude]);
}
In this case you will have to decode the URL to get the latitude and longitude.
Or you can pass the arguments in the query params:
routeWithData(id, latitude, longitude){
//console.log(latitude, longitude);
lat latlon = latitude + ', ' + longitude;
this.router.navigate(['/provider/bookings/'+id+'/details/map-location/', { queryParams: { latlon: latlon } }]);
}
See https://angular.io/guide/router#query-parameters-and-fragments for more details.

Related

google.maps.geometry.spherical.computeOffset error (a.lat is not a function)

I wanted a latlng value near a particular distance. I went throught the documentation of google maps api v3.
Have a look at my code :
generateCirclepolygon(){
for (let location of this.pointsLocation) {
let LatLng:any = {
lat: parseFloat(location.lat),
lng: parseFloat(location.lng)
};
let newpoints = [];
var polypoint = google.maps.geometry.spherical.computeOffset(LatLng , 3000 , 0)
console.log(polypoint , 'point');
}
}
After runing this code im getting ERROR TypeError: a.lat is not a function.
I'm sending a LatLng object to that which has lat and lng values and they are numbers. 3000 is the distance in meters and 0 is heading (i.e 0 degrees in clock wise from north).
I want the latlng value from my point to 3000 meters towards north. My main aim is to draw a circular polygon around a point by repeating this to get an array of points.
Related questions:
Google maps a.lat is not a function
Google Maps API a.lat is not a function error
Per the documentation, the computeOffset method takes a google.maps.LatLng as an argument:
computeOffset(from, distance, heading[, radius])
Parameters:
from: LatLng
distance: number
heading: number
radius (optional): number
Return Value: LatLng
Returns the LatLng resulting from moving a distance from an origin in the specified heading (expressed in degrees clockwise from north).
You are providing a LatLngLiteral (which doesn't have a .lat method, it has a .lat property.
let LatLng:any = {
lat: parseFloat(location.lat),
lng: parseFloat(location.lng)
};
should be:
let LatLng:any = new google.maps.LatLng(
parseFloat(location.lat),
parseFloat(location.lng)
);

Firebase query nearby object

In mysql, I was using haversine formula to query nearby object.
Using this formula
Formula
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance
FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;
Which
3959: radius of earth in miles
37,-122 : given lat lng
25: within 25 miles
In Firebase,
Can I store the users lat lng like what I did in mysql?
Create a marker table. id, lat, lng columns and then use the formula to query
Updated
I should ask, what is the way to query nearby using this formula in firebase.
Short answer, not like you want it to.
Firebase essentially has two ways to query for data: by path and by
priority. This is more limited than SQL, and there's a very good
reason for that — our API is carefully designed to only allow
operations we can guarantee to be fast. Firebase is a real-time and
scalable backend, and we want to enable you to build great apps that
can serve millions of users without compromising on responsiveness.
See, what is firebase and deNormalizing data
Also, this SO question is similar.
Response to comment:
Firebase will not calculate the sin( radians(X) ) for you. That's a 'slow' operation. So, you would need to store that information into the data when you save it.
I'm not 100% certain, but you could store the markers and the also store the longitude/latitude in a separate parent.
Root
-> Markers
-> longitude (Use the value as priority) -> MarkerId
-> latitude (Use the value as priority) -> MarkerId
Then you should be able to use bounding to find the Max and Min longitude and latitude.
Use that to query the longitude and latitude paths by priority. If a MarkerId exists in both, you use it.
A quick bit of research found this article on Latitude Longitude Bounding Coordinates
Hey I just finished building a real time google map using firebase and GeoFire. GeoFire is really cool and easy to use. It allows you to query using lon lat and radius. It returns a key that you can use to query your firebase db. You set the key, while you create the geoFire object, to be whatever you want. It is usually a ref that you can use to get the object that is associated with that distance.
Here is a link to geoFire:
https://github.com/firebase/geofire-js
Here is an example use case:
You have a lon lat, that you got using navigator:
var lon = '123.1232';
var lat = '-123.756';
var user = {
name: 'test user',
longitude: lon,
latitude: lat
}
usersRef.push(user).then(function(response) {
var key = response.key;
var coords = [lon, lat];
geoFire.set(key, coords, function(success){
console.log('User and geofire object has been created');
});
})
Now you can query for the user using:
// Set your current lon lat and radius
var geoQuery = geoFire.query({
center: [latitude, longitude],
radius: radiusKm
});
geoQuery.on('key_entered', function(key, location, distance) {
// You can now get the user using the key
var user = firebaseRefUrl + '/' + key;
// Here you can create an array of users that you can bind to a scope in the controller
});
If you are using google maps. I reccomend you use angular-google-maps.
Its a really cool google maps directive that takes in an array of markers and circles. So when ever $scope.markers or $scope.circles change in the controller it will automatically be applied to the map without any messy code. They have very good documentation.
Here is a link:
http://angular-ui.github.io/angular-google-maps/

Calculating a nearby street to use on streetview

I am facing an unusual problem where I need to calculate the latlong of a position on a map that has streetview imagery, without knowing the actual position.
I know the end destination of my user, but I need to calculate the latlong of a nearby position (approximately 1km away or less, this should be variable) that has streetview imagery and use that as the start destination.
An example would be that I know I need to go to Times Square, but I want to have a start destination that is about 1km away by road. I then need to verify that there is street view imagery for this co-ordinate before I decide that it's the starting point.
The function below recursively doubles the search distance, (up to a maximum of 10000 meters), until a panorama is found.
Sample code:
// Global vars
var G = google.maps;
var streetViewService = new G.StreetViewService();
function getNearSVP(latlon,maxDist) {
streetViewService.getPanoramaByLocation(latlon, maxDist, function(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
return data.location.latLng;
}
else{
if (maxDist < 10000){
maxDist = maxDist * 2;
return getNearSVP(latlon, maxDist);
}
else {
alert('StreetView is not available within '+maxDist+' meters of this location');
}
}
});
}
Live demo here

Draw Route X Kilometers from Origin

Running/walking distance display.
User enters a location and a distance.
I can overlay a circle with a radius of the distance the user entered, with the user's location as the center point.
I can set four cardinal points (N, S, E, W) around the point of origin at the distance the user set and draw the routes to those points, such that point B is 100KM from point A, but the mapped route is, say, 145km along the road.
Is it possible to display a route along the road exactly 100km?
Edited to update progress.
Finally solved this and thought I'd share.
so, the user supplies a location and a distance; we'll say 100Km.
The code finds cardinal points 100Km N, S, E, W of the point of origin, then solves routes to each point. If solving for the route is successful, the result contains an array of points from the point of origin to the destination.
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result) {
renderDirections(result);
});
//don't use the google api DirectionsRender() to draw the route.
//instead - result holds an array of lat/long points that make up the entire route. Lets say it's latlong[123]
//iterate through that array, getting a distance from point A to latlong[0], A to latlong[1], etc...
//when that distance is >= user supplied distance, STOP, and draw a polyline from point A through the latlong points in the array latlong[78]
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
if(myroute)
{
//create a LatLon from the Starting point
var objGeo = new LatLon(Geo.parseDMS(myroute.overview_path[0].Qa), Geo.parseDMS(myroute.overview_path[0].Ra));
//call get distance from the starting point to each other point in the array
//each subsequent point should be a longer distance
var arrPointsToDraw =[];
for(var i = 1; i<=myroute.overview_path.length-1;i++)
{
try
{
var objGeo2 = new LatLon(Geo.parseDMS(myroute.overview_path[i].Qa), Geo.parseDMS(myroute.overview_path[i].Ra));
}
catch(err)
{
alert(err.description);
}
//here, total = kilometers
total = objGeo.distanceTo(objGeo2,3);
//add coordinates to our array of points that we are going to draw
arrPointsToDraw.push(new google.maps.LatLng(objGeo2._lat, objGeo2._lon));
if(parseInt(total) > parseInt(distance.value))
{
arrPointsToDraw.pop();//remove the last element of the array
break;
}
}
//at this point, arrPointsToDraw[] contains the lat/long points that are closest to our distance
//without going over
lines[lines.length] = new google.maps.Polyline({
path: arrPointsToDraw,
strokeColor: '#1589FF',
strokeOpacity: 1.0,
strokeWeight: 3
});
lines[lines.length-1].setMap(map);
}//end if(myRoute)
}
This code makes use of two fantastic collections of functions found here

OpenLayers: parsed GeoJSON points always display at coords(0 , 0)

this is the first time i use OpenLayers and i don't understand what i'm doing wrong.
I try to display a simple point parsed from GeoJSON. The data seems to be parsed correctly (i checked with the console) but whatever point i give, it always displays at a position i guess to be LonLat(0,0) on my vector layer.
What am i doing wrong ?
var map, baseLayer, placesLayer, geojsonParser ;
// data below have been simplified and reformated to enhance readability
var geojsonData =
{
"type":"Feature",
"geometry":
{
"type":"Point",
"coordinates":[-4.0280599594116,5.3411102294922]
},
"properties":
{
"id":273,
"name":"ABIDJAN"
}
};
$(document).ready(function(){
map = new OpenLayers.Map('map');
baseLayer = new OpenLayers.Layer.OSM();
placesLayer = new OpenLayers.Layer.Vector();
geojsonParser = new OpenLayers.Format.GeoJSON();
placesLayer.addFeatures(geojsonParser.read(geojsonData));
map.addLayers([baseLayer,placesLayer]);
map.setCenter(
new OpenLayers.LonLat(-4, 5.3).transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
), 5
);
}); // document ready
This is the right solution:
var geojson_format = new OpenLayers.Format.GeoJSON({
'internalProjection': new OpenLayers.Projection("EPSG:900913"),
'externalProjection': new OpenLayers.Projection("EPSG:4326")
});
source: https://gist.github.com/1118357
Hi it sounds like you need to transform the long/lat coordinaites into the correct display coordinates:
You can either declare the projections and then transform your geometry feature:
var projWGS84 = new OpenLayers.Projection("EPSG:4326");
var proj900913 = new OpenLayers.Projection("EPSG:900913");
feature.geometry.transform(projWGS84, proj900913);
Or get the map projection "on the fly" more like this:
var projWGS84 = new OpenLayers.Projection("EPSG:4326");
feature.geometry.transform(projWGS84, map.getProjectionObject());
Obviously if you are using a different input projection from me change "ESPG:4326" to whatever you require.
HTH
C
EDIT:
In your case you would need to write something like:
geojsonData.geometry.transform(projWGS84, map.getProjectionObject());

Resources