Get coordinates, measure distances, and compare them - javascript

It was proposed to develop a page where you present an excerpt of Google Maps with several markers organized in clusters (done). I do not have experience with javascript, and what I need is that clicking a button or not, it is possible to get my location and automatically be informed of which point marked on the map is closer to me. Can someone help me?
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: {lat: 40.963308, lng: -8.594651}
});
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
{lat: 40.962157, lng: -8.593313},
{lat: 40.962149, lng: -8.595695},
{lat: 40.960351, lng: -8.598922},
{lat: 40.967305, lng: -8.591450},
{lat: 40.961682, lng: -8.608136}
]
</script>

If you are talking about the aerial distance, use the Euclidean formula on all, pretty fast, considering everything. Just modify it a little, so you don't use the square root, as it is an expensive operation.
(Xpos - Xpoint)^2 + (Ypos - Ypoint)^2
Apply a basic min alogirthm, i.e. always save the lowest distance point.
That's the easy way, generally also the nearest point, if taking places far away.
The way to do the road distance previously would have been to do it one by one, but Google thankfully thought of this case and developed https://developers.google.com/maps/documentation/distance-matrix/intro
I am not sure what the usage quota for your account will be, but that's upto you and your company to figure out depending on the type of plan you want.

Related

Google Maps v3 - Limit area where a function can work

In my javascript code using Google Maps API v3 I tried to set bounds to the Autocomplete function, it works quite well infact as soon as I type a letter in the input field (html), the same autocomplete advise me with addresses that can be found in the bounds area, however if I type the name of a city that is outside bounds limit I get advice also for that and other cities. Is there a way to avoid this? I'd like to have only advice for my "bounds".
Here is the piece of code:
init = function() {
var latlng = new google.maps.LatLng(40.635636, 17.942414);
var mapOptions = { zoom: 13, center: latlng, minZoom: 10, maxZoom: 16};
default_bounds = new google.maps.LatLngBounds();
default_bounds.extend(new google.maps.LatLng(40.635636-0.33, 17.942414-0.33));
default_bounds.extend(new google.maps.LatLng(40.635636+0.33, 17.942414+0.33));
console.log("Initialing map at: 40.635636, 17.942414");
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
originAutocomplete = new google.maps.places.Autocomplete(document.getElementsByName("origin")[0], {types: ['geocode']});
destinationAutocomplete = new google.maps.places.Autocomplete(document.getElementsByName("destination")[0], {types: ['geocode']});
originAutocomplete.setBounds(default_bounds);
destinationAutocomplete.setBounds(default_bounds);
}
Correct image: (show only places in Puglia south Italy)
Incorrect image: (show places of many different regions)
According to the documentation, there are 4 ways to set biases and search-area boundaries for Autocomplete, and they are
* Set the bounds on creation of the Autocomplete object.
* Change the bounds on an existing Autocomplete.
* Set the bounds to the map's viewport.
* Restrict the search to a specific country.
Since the first 3 options would only bias, but not restrict the result, you can only filter out other country's information, but not cities from the same country.
Note that you might able to modify the result by playing with the return object, but that is a violation of the ToS.

GoogleMaps - multiple markers with multiple colors

I'm trying to make a nice google map with some markers on it. I've found some really convinient solution in the web, which covers almost my every need :D I'd like to colorize pin/markers on the map.
Well, tried to make a working jsfiddle, but unfortunately, something went wrong :( so you wouldn't see the map, but there are all codes :)
http://jsfiddle.net/hf37ftra/9/
// Multiple Markers
var markers = [
['Marker_name', 51.113882,17.070474],
];
this part is responsible for showing multiple markers, can I somehow define here the color of the marker (I know it is possible, because I've found tutorials to change ALL the markers colors, but I'd like to make let's say 4-5 different coloured markers)?
Later in the code is part for custom info box for every marker, so maybe it could be done that way :)
thanks!
You may use something like :
var markers = [
['Starter', 51.113882,17.070474,'icon1.png'],
];
and change your constructor to :
[...]
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0],
icon: markers[i][3]
});
In your for loop:
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
You can add extra line there:
icon: 'brownMarker.png'
Well, I love being on stackoverflow, when I can learn everyday something new with just some little help from others :)
// Multiple Markers
var markers = [
['Title', 51.113882,17.070474, 'http://youriconaddress'],
];
and then, in part:
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0],
icon: markers[i][3] // [3] tells JS to take third 'argument' from markers variable, from each one.
});
That way you can add as many arguments as you want, having a really nice and simple tool to make nicer google maps!

Convert zip code to latitude/longitude coordinates using Google Maps API?

I've been looking through the docs and all over the web for an example of this and I can't find an example of this use-case.
Given a zip code, I need a rough approximation of the user's location in the form of lat/long coordinates. All I have is the zip code, nothing else.
Can this be done using Google Maps API? If not, what other resources would you suggest looking at?
You can pass any text as the address key for the geocoder. If the geocoding is successsful, you should get an array of results.
From then on you can pick the first result or iterate over the array. Each of its elements should contain an address object, and postal code is one posible field on that obj.
Keep in mind that usps zipcodes are not points nor shapes. They are arrays of points, and the centroid of the polygon drawn by using those points as vertexes probably doesn't have any special meaning.
maybe you can do this by php with the following script:
function getLnt($zip){
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($zip)."&sensor=false";
$result_string = file_get_contents($url);
$result = json_decode($result_string, true);
$result1[]=$result['results'][0];
$result2[]=$result1[0]['geometry'];
$result3[]=$result2[0]['location'];
return $result3[0];
}
if you call this function by (* I filtered out the space between chars, it isn't necessary):
$coords = str_replace(' ','',$foo->zipcode);*
$val = getLnt($coords);
/* print latitude & longitude for example */
print $val['lat'];
print $val['lng'];
Then after that u can mix it with your google map script like:
function initialize(){
var myLatlng = new google.maps.LatLng(<?= $val['lat'] ?>,<?= $val['lng'] ?>);
var mapOptions = {
zoom: 14,
center: myLatlng,
disableDefaultUI: true,
scrollwheel: false,
}
var map = new google.maps.Map(document.getElementById('propMap'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'title of location',
icon: iconBase + 'google-marker.png'
});
}
Note: This worked fine for me, but maybe there are better ways to do this ;-)

Google Maps Radius

I'd like to know if it's possible to put a radius delimiter in Google maps!?
For example: I select a region or a city and I had a 5 mile radius and the delimiter increases, drawing it!
Please consider this example: I choose "Amsterdam" as the place, and then I add 5km to it and it will return the results from "Amsterdam" plus the 5km radius
http://www.funda.nl/koop/amsterdam/+5km/
My problem is I dont understand how to add 5km to "Amsterdam" since it cant be the center point - I think I need the delimiter for the region "Amsterdam". Does this exist on Google maps API or any other API?
Update:
Map Charts
as per your requirement, i think the above link will help you.
Try this,
// Create marker
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(39.7433,-104.9872),
title: 'Some location'
});
// Add circle overlay and bind to marker
var circle = new google.maps.Circle({
map: map,
radius: 8047, // 5 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', marker, 'position');
Reference:
http://seriouscodage.blogspot.in/2010/11/visualizing-data-as-circles-in-google.html

Get N Markers that are closest to the center in Google Maps

I'm trying to figure out how to sort the first 10 Markers on a Google map by distance from the center of the map in Javascript. So, let's say I have 100 Markers in an array, and I want to display more information about the first 10 closest markers in a HTML unordered list. How would I go about doing that?
I found a similar example for Google Maps API version 2 here, but nothing for version 3.
Whatever happens You need to calculate all distances. You can do it yourself with simple equations or use Google's geometry library: http://code.google.com/intl/pl-PL/apis/maps/documentation/javascript/geometry.html and its function: computeDistanceBetween(). Then store distance in custom marker property like e.g:
marker.distance = google.maps.geometry.spherical.computeDistanceBetween(marker.position, center.position);
and sort it anyway you want.
Hope it helps.
Sort the array by proximity to your map's centre point. Use sort().
Slice the first 10 with slice().
Plot these on the map.
There are a few questions like this on StackOverflow but none of them really show a complete example that is easy to read and understand, so I put one together. This is using the lodash/underscore sortBy function for the sorting.
const map = new google.maps.Map('#map', { center: { lat: 47.6541773, lng: -122.3500004 } });
const markers = [
new google.maps.Marker({ position: { lat: 47.6485476, lng: -122.3471675 }, map }),
new google.maps.Marker({ position: { lat: 47.6606304, lng: -122.3651889 }, map })
// ...
];
const sortedMarkers = _.sortBy(markers, marker => {
google.maps.geometry.spherical.computeDistanceBetween(
marker.position,
map.getCenter()
)
});
const firstTenSortedMarkers = sortedMarkers.slice(10);
The sortBy function iterates through each marker in the array and sorts the list based on the value returned by the function that is it's second argument. The computeDistanceBetween function returns a number representing the distance in meters between the map center and the marker position, which is easy to sort on.

Categories

Resources