I have downloaded a google maps plugin for wordpress, which outputs in km, but I'm in the UK so I need miles.
I have added the line
unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL
to the code
function calcRoute() {
var start = document.getElementById('origin').value;
var end = document.getElementById('destination').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL
};
but it still returns km.
Any ideas how I get it to return miles?
We don't know what value you are checking but if we are talking about the Distance object, the documentation says the value property is always returned in meters, while the text property is a representation of the value using the UnitSystemspecified.
https://developers.google.com/maps/documentation/javascript/reference#Distance
Otherwise, you always can convert from METRIC to IMPERIAL using your own maths.
Related
I have problem during working in Google Earth Engine. I was processing some vector files. And i am getting below code:
The geometry has too many vertices. You can try to simplify it using:
// Get a feature collection and subset the first feature.
var feature = ee.FeatureCollection("TIGER/2018/States").first();
// Simplify the feature - think of max error as resolution.
// Setting to 100 means that the geometry is accurate to
// within 100 meters, for example.
var featureSimple = ee.Feature(feature).simplify({maxError: 100});
or for a ee.FeatureCollection:
// Get a feature collection.
var featureCol = ee.FeatureCollection("TIGER/2018/States");
// Simplify each feature in the collection, by mapping the
// .simplify() function over it.
var simplifiedCol = featureCol.map(function(feature) {
return feature.simplify({maxError: 100});
});
I'm using google apps script to code a distance finder for Google Maps. I've found examples of such, but they keep failing, so I thought I'd code my own. Sadly, this is failing with the same error:
TypeError: Cannot read property "legs" from undefined. (line 16).
It seems to be that it's sometimes working, and sometimes not. I have a few (3) places in my sheet that are calling the same functions, and at times one or more will return a valid response.
I saw elsewhere that people were suggesting using an API key to make sure that you get a good response, so that's what I've implemented below. (api keys redacted! is there a good way to tell if they've been recognised?)
Any ideas what might be going awry?!
Thanks in advance,
Mike
function mikeDistance(start, end){
start = "CV4 8DJ";
end = "cv4 9FE";
var maps = Maps;
maps.setAuthentication("#####", "#####");
var dirFind = maps.newDirectionFinder();
dirFind.setOrigin(start);
dirFind.setDestination(end);
var directions = dirFind.getDirections();
var rawDistance = directions["routes"][0]["legs"][0]["distance"]["value"];
var distance = rawDistance/1609.34;
return distance;
}
Here's my short term solution while the issue is being fixed.
Not ideal, but at least reduces using your API limit as much as possible.
function getDistance(start, end) {
return hackyHack(start, end, 0);
}
function hackyHack(start, end, level) {
if (level > 5) {
return "Error :(";
}
var directions = Maps.newDirectionFinder()
.setOrigin(start)
.setDestination(end)
.setMode(Maps.DirectionFinder.Mode.DRIVING)
.getDirections();
var route = directions.routes[0];
if (!route) return hackyHack(start, end, level+1); // Hacky McHackHack
var distance = route.legs[0].distance.text;
// var time = route.legs[0].duration.text;
return distance;
}
I am using DirectionRenderer(gmap3) to show the user directions. The problem is it shows a match even if it cannot find an exact match. Eg: SomeFakePlace, myRealCity will match myRealCity even if it cannot match SomeFakePlace.
So it shows the directions from City's center to the place, instead. The destination is fixed(myLatLng)
I want it to return null and not show a route if cannot find one. I have decent error display to handle that.
$("#map-canvas-single").gmap3({
getroute:{
options:{
origin:$("#directions-from").val(),
destination:myLatlng,
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
callback: function(results){
console.log(results);
var point= results.routes[0].overview_path[0]
window.directionMarker = new google.maps.Marker({
position: new google.maps.LatLng(point.jb,point.kb),
title:$("#directions-from").val(),
//icon:"http://maps.google.com/mapfiles/ms/icons/<?php if($this->listing->type=="pg"):?>green<?php else: ?>purple<?php endif;?>-dot.png"
});
window.directionMarker.setMap($(this).gmap3("get"));
if(!results)
noty({text:"Place not found!",type:"error"});
else
{
$(this).gmap3({
directionsrenderer:{
container: $("#directions-container"),
id:"directions",
options:{
directions:results,
suppressMarkers :true //<<Look here>>
}
}
});
}
}
}
});
The code works fine and all. I think this the fault of direction renderer service, not gmaps. I am sure htere must be some parameter for an exact match
I'm not familiar with Google Maps API, but what I'd do is do a geocode lookup on the source address and find the lat, lng. You'll usually get coordinates with levels of confidence, so you can have a minimum threshold below which to throw an error.
https://developers.google.com/maps/documentation/geocoding/
Also, don't forget mapquest.
http://developer.mapquest.com/web/products/dev-services/geocoding-ws
I tried to search for all cities within a visible map's bounds. How can I do that?
Below is what I tried to do:
$.fn.gmap3.geocoder.geocode({ 'address': 'Georgia' }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
globalMap.setCenter(results[0].geometry.location);
var resultBounds = new google.maps.LatLngBounds(
results[0].geometry.viewport.getSouthWest(),
results[0].geometry.viewport.getNorthEast()
);
globalMap.fitBounds(resultBounds);
// get cities in the map
var service = new google.maps.places.PlacesService(globalMap);
var request = {
bounds: resultBounds,
types: ['locality']
};
service.search(request, function (results, status) {
debugger;
});
}
});
But the result is ZERO_RESULTS. Maybe the reason is that the results are restricted to a radius of 50.000 meters?
Anyone knows how to solve my problem? Thanks a lot.
--UPDATE--
Thank, Sean, for reading my post carefully and give detail feedback.
This is how I refer to the lib:
src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"
I also added more detail to the geocode function to get more precise result. But I still don't get the results I want.
Check the list in this page: https://developers.google.com/places/documentation/supported_types, I realize that almost all items in the first list returns values but not for the second list. The only item return value is 'political' and it returns only 1 instead of 20.
This is my code after modifing:
this.setCenterByAddress = function (address, region) {
$.fn.gmap3.geocoder.geocode({ 'address': address, 'region': region }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
globalMap.setCenter(results[0].geometry.location);
var resultBounds = new google.maps.LatLngBounds(
results[0].geometry.viewport.getSouthWest(),
results[0].geometry.viewport.getNorthEast()
);
globalMap.fitBounds(resultBounds);
// get cities in the map
var service = new google.maps.places.PlacesService(globalMap);
var request = {
bounds: resultBounds,
types: ['country',
'administrative_area_level_1',
'administrative_area_level_2',
'administrative_area_level_3',
'colloquial_area',
'country',
'floor',
'geocode',
'intersection',
'locality',
'natural_feature',
'neighborhood',
'political',
'point_of_interest',
'post_box',
'postal_code',
'postal_code_prefix',
'postal_town',
'premise',
'room',
'route',
'street_address',
'street_number',
'sublocality',
'sublocality_level_4',
'sublocality_level_5',
'sublocality_level_3',
'sublocality_level_2',
'sublocality_level_1',
'subpremise',
'transit_station']
};
service.search(request, function (results, status) {
debugger;
});
}
});
}
MORE INFO: The same value return even when location and radius is used. And I use free map and receive "OVER_QUERY_LIMIT" all the time.
You shouldn't be limited to 50,000 meters unless you use the location and radius option, which you are not; you are using bounds. I suggest backing out a level and digging into the results that are returned from the starting call to geocode, because your usage of the PlacesService appears to be correct. What are the values internal to the resultBounds object? I also notice that you aren't using region biasing when you call the geocoder and it may be that "Georgia" is not sufficiently specific. For example, do you mean the region within the Russian Federation or the US state? And I'm not sure what URL you are using to load the Google Maps API & places library, but that could also be effecting your results.
I'd double-check the results coming back from the geocoder, because unless I am missing something, it looks like your basic approach is sound.
You can't return more than two near by localities around a particular latitude-longitude with Geocoding API/Places API
Please see this thread on Google Places API forum
This is not possible with the Google Places API as political results
such as locality, neighbourhood and sublocality are returned to
identify the area of the request and are limited to two per request.
I want to display a couple of routes on a map, but I would prefer to first draw them with google maps. For example, I got directions from Seattle to San Diego, then moved things a bit, and the link looks like this.
I know that I can use the DirectionsRenderer to draw a polyline connecting Seattle and San Diego like this:
function renderDirections(result) {
var directionsRenderer = new google.maps.DirectionsRenderer;
directionsRenderer.setMap(gMap);
directionsRenderer.setDirections(result);
}
var directionsService = new google.maps.DirectionsService;
function requestDirections(start, end) {
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.BICYCLING
}, function(result) {
renderDirections(result);
});
}
requestDirections('Seattle, WA', 'San Diego, CA');
What I would like to know is if there is a way to pass in the link as the directions request. The link contains waypoints, my modifications to the default route.
It is possible and you are on the right track. It is hard to understand the API. I believe that you have to set the waypoints in the DirectionRequest object of the DirectionsService when you call the route method. I don't think you can pass in a link, but you can create an object or Array of waypoints first.
If you want, you can also specify the optimizeWaypoints boolean.
Check out the DirectionsRequest Object.
waypoints Array. Array of intermediate waypoints. Directions will be calculated from the origin to the destination by way of each waypoint in this array. Optional.
Yes, you can use the DirectionsRenderer so long as you pass your start and end points into a DirectionsRequest, and pass that into a DirectionsService object. Once you call .setDirections it'll draw the polyline for you. From the API documentation at.
Set the renderer to use the result from the DirectionsService. Setting a valid set of directions in this manner will display the directions on the renderer's designated map and panel.
If what you were getting at was drawing the polyline yourself (though I don't see why it would be necessary), the individual points in the path can be derived -- DirectionsResult contains an array of DirectionsLegs which contains an array of DirectionsSteps which contains a .path property, which is an array of latlngs. (whew!)