Google Maps API - Getting Closest Points to Zipcode

Google Maps API - Getting closest points to zipcode

The usual solution is to use the google.maps.geometry.spherical library computeDistanceBetween(from:LatLng, to:LatLng, radius?:number) method to reduce the number to about 10, then use the distance matrix return the driving distance to those locations so the results can be sorted by driving distance (actual travel distance), and reduced to the closest 3 to 5 locations by actual travel distance within the request limits.

example (finds the 3 closest places from a list)
(data borrowed from the FusionTables "pizza store" example)

  function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (customerMarker) customerMarker.setMap(null);
customerMarker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
closest = findClosestN(results[0].geometry.location,10);
// get driving distance
closest = closest.splice(0,3);
calculateDistances(results[0].geometry.location, closest,3);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}

function findClosestN(pt,numberOfResults) {
var closest = [];
document.getElementById('info').innerHTML += "processing "+gmarkers.length+"<br>";
for (var i=0; i<gmarkers.length;i++) {
gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt,gmarkers[i].getPosition());
document.getElementById('info').innerHTML += "process "+i+":"+gmarkers[i].getPosition().toUrlValue(6)+":"+gmarkers[i].distance.toFixed(2)+"<br>";
gmarkers[i].setMap(null);
closest.push(gmarkers[i]);
}
closest.sort(sortByDist);
return closest;
}

function sortByDist(a,b) {
return (a.distance- b.distance)
}

function calculateDistances(pt,closest,numberOfResults) {
var service = new google.maps.DistanceMatrixService();
var request = {
origins: [pt],
destinations: [],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
};
for (var i=0; i<closest.length; i++) request.destinations.push(closest[i].getPosition());
service.getDistanceMatrix(request, function (response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('side_bar');
outputDiv.innerHTML = '';

var results = response.rows[0].elements;
for (var i = 0; i < numberOfResults; i++) {
closest[i].setMap(map);
outputDiv.innerHTML += "<a href='javascript:google.maps.event.trigger(closest["+i+"],\"click\");'>"+closest[i].title + '</a><br>' + closest[i].address+"<br>"
+ results[i].distance.text + ' appoximately '
+ results[i].duration.text + '<br><hr>';
}
}
});
}

example above with "Get Directions" link in the infoWindow

How to search for all points in a given radius of a zipcode with google maps api?

Here are the two high-level steps you need to follow to implement this:

1) You want to convert that zipcode (or an address in many different forms!) to a latitude and longitude coordinate using the Google Geocoder API.

2) Dynamically create a GET request to a script that queries your database based on the distance the user entered (5 miles, 10 miles, etc.) like so:

var searchUrl = 'phpsqlajax_search.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;

Look at my answer to this related question so you can take user input and geocode the address: Store locatore, how to use/input my postion?

The Google Maps API provides extensive documentation on finding the closest items in a database to a certain latitude and longitude coordinate. It can be found here: https://developers.google.com/maps/articles/phpsqlsearch_v3

Note: The documentation uses PHP, Javascript, and MySQL.

Nearest marker to designated zip or address Google Maps

Google provides the computeDistanceBetween function to calculate the straight-line distance between two google.maps.LatLng points.

Modify your script tag to include the optional geometry library:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&v=3&libraries=geometry"></script>

Then call the computeDistanceBetween as such:

var distanceInMeters = google.maps.geometry.spherical.computeDistanceBetween(origin, dest);

Dev docs @ https://developers.google.com/maps/documentation/javascript/geometry#Distance

If you want to calculate the actual travel distance/time, you need to use the Google Distance Matrix API. (As @Yamaha32088 mentions, the Distance Matrix API has very strict quota limits which you may quickly exceed depending on your license.)

See https://developers.google.com/maps/documentation/distancematrix/ for more info on the distance matrix API.

Get nearest location from a set of predefined locations with Google Maps Javascript API

Update:

Keyless access to Google Maps Platform is now deprecated. You will need to have an API key with all your API calls to avoid service interruption . For further details please refer to http://g.co/dev/maps-no-account


Original Answer:

I was able to solve this in following way:

  1. Get lat, long co-ordinates of the input zipcode from this URL:
    http://maps.googleapis.com/maps/api/geocode/json?address=zipcode
    (add zipcode)
  2. Take average of the lats and longs of northeast and southwest returned in the response of this URL. Consider the calculated average lat and long as the input co-ordinates.
  3. Compute the distance to get the closest location using google.maps.geometry.spherical.computeDistanceBetween()
  4. Initialize the Google Map with all of the markers.
  5. Use google.maps.LatLngBounds() to adjust the zoom so that the map includes the input zipcode's location and the nearest searched location.

Here's a demo. The H icon stands for the input zipcode location and C icon stands for the closest location among the searched ones. (For now, I have kept only 2 predefined locations).

var predefinedLocations = [{    "name": "Brookwood Medical Center",    "lat": 33.4636415,    "lng": -86.7771671  },  {    "name": "Lutheran Medical Center",    "lat": 40.646872,    "lng": -74.020892  }];
$("form#zipcodeSearch").on("submit", function(event) { event.preventDefault(); var jsonUrl = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + $("input#zipcode").val();
$.ajax({ type: "POST", headers: { 'Accept': 'application/json', 'Content-Type': 'text/plain' }, dataType: "json", url: jsonUrl, success: function(data) {
var lat = (data.results[0].geometry.bounds.northeast.lat + data.results[0].geometry.bounds.southwest.lat) / 2; var lng = (data.results[0].geometry.bounds.northeast.lng + data.results[0].geometry.bounds.southwest.lng) / 2; var p1, p2;
predefinedLocations.forEach(function(obj) { p1 = new google.maps.LatLng(obj.lat, obj.lng); p2 = new google.maps.LatLng(lat, lng);
obj.distance = calcDistance(p1, p2); });
// sort by distance var locationInfo = predefinedLocations.sort(compare);
//console.log('locationInfo', locationInfo);
initializeGoogleMap(locationInfo, lat, lng);
} });
});
var map;
function initializeGoogleMap(locationInfo, lat, lng) { var mapOptions = { zoom: 15 }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// zoom to only the input zipcode and closest location var latlngbounds = new google.maps.LatLngBounds(); latlngbounds.extend(new google.maps.LatLng(locationInfo[0].lat, locationInfo[0].lng)); latlngbounds.extend(new google.maps.LatLng(lat, lng)); map.fitBounds(latlngbounds);
var infowindow = new google.maps.InfoWindow();
var marker, i;
// set marker for input location setMarker(lat, lng, map, 'http://www.lsac.org/images/default-source/mainportalimages/icon-h-grey-bg.jpg?sfvrsn=2', "You are here!", i, infowindow);
// set marker for closest location setMarker(locationInfo[0].lat, locationInfo[0].lng, map, 'http://alert.mta.info/sites/all/themes/mta/images/subway_bullets/c.png', locationInfo[0].name, i, infowindow);
for (var j = 1; j < locationInfo.length; j++) { // set marker for other location setMarker(locationInfo[j].lat, locationInfo[j].lng, map, '', locationInfo[j].name, i, infowindow); }
}
function calcDistance(p1, p2) { return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);}
function compare(a, b) { if (parseFloat(a.distance) < parseFloat(b.distance)) { return -1; }
if (parseFloat(a.distance) > parseFloat(b.distance)) { return 1; }
return 0;}
function setMarker(lat, lng, map, icon, content, i, infowindow) {
var marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, lng), map: map, icon: icon });
google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent(content); infowindow.open(map, marker); } })(marker, i));
}
* {  margin: 0;  padding: 0;}
html { font-size: 62.5%; /* so, 10px = 1rem */}
body { font-family: arial;}
#map-canvas { z-index: -1; position: absolute; top: 0; height: 100%; width: 100%;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry"></script>
<form id="zipcodeSearch"> <input type="text" id="zipcode" placeholder="Enter zipcode here" /> <input type="submit" value="Search" /></form>
<div id="map-canvas"></div>

Google Maps API - Closest marker function change to closest n markers

You could use the (slightly modified) findClosestN function from this question (changed gmarkers to markers, changed the function to return the closest array limited to numberOfResults elements)

function findClosestN(pt, numberOfResults) {
var closest = [];
for (var i = 0; i < markers.length; i++) {
markers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt, markers[i].getPosition());
markers[i].setMap(null);
closest.push(markers[i]);
}
closest.sort(sortByDist);
return closest.splice(0,numberOfResults);
}

function sortByDist(a, b) {
return (a.distance - b.distance)
}

proof of concept fiddle

code snippet:

var geocoder = null;
var map = null;
var customerMarker = null;
var markers = [];
var closest = [];

function initialize() {
// alert("init");
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: new google.maps.LatLng(52.6699927, -0.7274620),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();
document.getElementById('info').innerHTML = "found " + locations.length + " locations<br>";
for (i = 0; i < locations.length; i++) {
var coordStr = locations[i][4];
var coords = coordStr.split(",");
var pt = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
bounds.extend(pt);
marker = new google.maps.Marker({
position: pt,
map: map,
icon: locations[i][5],
address: locations[i][2],
title: locations[i][0],
html: locations[i][0] + "<br>" + locations[i][2]
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(marker.html);
infowindow.open(map, marker);
}
})
(marker, i));
}
map.fitBounds(bounds);

}

function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
if (customerMarker) customerMarker.setMap(null);
customerMarker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
var numResults = parseInt(document.getElementById('numberResults').value);
closest = findClosestN(results[0].geometry.location, numResults);
for (var i = 0; i < closest.length; i++) {
closest[i].setMap(map);
}
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}

function findClosestN(pt, numberOfResults) {
var closest = [];
for (var i = 0; i < markers.length; i++) {
markers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt, markers[i].getPosition());
markers[i].setMap(null);
closest.push(markers[i]);
}
closest.sort(sortByDist);
return closest.splice(0, numberOfResults);
}

function sortByDist(a, b) {
return (a.distance - b.distance)
}

google.maps.event.addDomListener(window, 'load', initialize);

var locations = [
["John's Pizza", "no", "400 University Ave, Palo Alto, CA", "<Polygon><outerBoundaryIs><LinearRing><coordinates>-122.121277,37.386799,0 -122.158012,37.4168,0 -122.158012,37.448151,0 -122.142906,37.456055,0 -122.118874,37.45224,0 -122.107544,37.437793,0 -122.102737,37.422526,0 -122.113037,37.414618,0 -122.121277,37.386799,0 </coordinates></LinearRing></outerBoundaryIs></Polygon>", "37.447038,-122.160575", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
["JJs Express", "yes", "1000 Santa Cruz Ave, Menlo Park, CA", "<Polygon><outerBoundaryIs><LinearRing><coordinates>-122.200928,37.438611,0 -122.158012,37.4168,0 -122.158012,37.448151,0 -122.142906,37.456055,0 -122.144623,37.475948,0 -122.164192,37.481125,0 -122.189255,37.478673,0 -122.208481,37.468319,0 -122.201271,37.438338,0 </coordinates></LinearRing></outerBoundaryIs></Polygon>", "37.448638,-122.187176", "http://maps.google.com/mapfiles/ms/icons/green.png"],
["John Paul's Pizzeria", "no", "1100 El Camino Real, Belmont, CA", "<Polygon><outerBoundaryIs><LinearRing><coordinates>-122.304268,37.516534,0 -122.300835,37.505096,0 -122.262383,37.481669,0 -122.242813,37.502917,0 -122.244186,37.534232,0 -122.269249,37.550021,0 -122.291222,37.545122,0 -122.302895,37.537499,0 -122.304268,37.516534,0 </coordinates></LinearRing></outerBoundaryIs></Polygon>", "37.520436,-122.275978", "http://maps.google.com/mapfiles/ms/icons/red.png"],
["JJs Express", "yes", "300 E 4th Ave, San Mateo, CA", "<Polygon><outerBoundaryIs><LinearRing><coordinates>-122.304268,37.516534,0 -122.348557,37.538044,0 -122.359886,37.56363,0 -122.364006,37.582405,0 -122.33654,37.589207,0 -122.281609,37.570433,0 -122.291222,37.545122,0 -122.302895,37.537499,0 -122.304268,37.516534,0 </coordinates></LinearRing></outerBoundaryIs></Polygon>", "37.564435,-122.322080", "http://maps.google.com/mapfiles/ms/icons/green.png"],
["John's Pizza", "yes", "1400 Broadway Ave, Burlingame, CA", "<Polygon><outerBoundaryIs><LinearRing><coordinates>-122.374306,37.548933,0 -122.348557,37.538044,0 -122.359886,37.56363,0 -122.364006,37.582405,0 -122.33654,37.589207,0 -122.359543,37.59764,0 -122.372246,37.604712,0 -122.417564,37.594648,0 -122.374306,37.548933,0 </coordinates></LinearRing></outerBoundaryIs></Polygon>", "37.584935,-122.366182", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
["JJs Express", "yes", "700 San Bruno Ave, San Bruno, CA", "<Polygon><outerBoundaryIs><LinearRing><coordinates>-122.462883,37.628916,0 -122.445374,37.639247,0 -122.426147,37.648762,0 -122.405205,37.642238,0 -122.400055,37.628644,0 -122.392159,37.610696,0 -122.372246,37.604712,0 -122.417564,37.594648,0 -122.462196,37.628644,0 </coordinates></LinearRing></outerBoundaryIs></Polygon>", "37.630934,-122.406883", "http://maps.google.com/mapfiles/ms/icons/green.png"],
["JJs Express", "yes", "300 Beach St, San Francisco, CA", "<Polygon><outerBoundaryIs><LinearRing><coordinates>-122.43576,37.790795,0 -122.449493,37.801646,0 -122.425461,37.809784,0 -122.402115,37.811411,0 -122.390442,37.794593,0 -122.408295,37.79188,0 -122.434387,37.789167,0 </coordinates></LinearRing></outerBoundaryIs></Polygon>", "37.807628,-122.413782", "http://maps.google.com/mapfiles/ms/icons/green.png"],
["JJs Express", "yes", "1400 Haight St, San Francisco, CA", "<Polygon><outerBoundaryIs><LinearRing><coordinates>-122.463398,37.760266,0 -122.477349,37.774785,0 -122.427349,37.774785,0 -122.429237,37.763658,0 -122.46357,37.760808,0</coordinates></LinearRing></outerBoundaryIs></Polygon>", "37.770129,-122.445082", "http://maps.google.com/mapfiles/ms/icons/green.png"],
["JJs Express", "yes", "2400 Mission St, San Francisco, CA", "<Polygon><outerBoundaryIs><LinearRing><coordinates>-122.418766,37.747779,0 -122.425289,37.768951,0 -122.406063,37.769901,0 -122.406063,37.749679,0 -122.418251,37.747508,0 </coordinates></LinearRing></outerBoundaryIs></Polygon>", "37.758630,-122.419082", "http://maps.google.com/mapfiles/ms/icons/green.png"],
["JJs Express", "yes", "500 Castro St, Mountain View, CA", "<Polygon><outerBoundaryIs><LinearRing><coordinates>-122.121277,37.386799,0 -122.108917,37.362244,0 -122.077675,37.3385,0 -122.064285,37.378615,0 -122.069778,37.3898,0 -122.076645,37.402619,0 -122.078705,37.411619,0 -122.113037,37.414618,0 -122.121277,37.386799,0 </coordinates></LinearRing></outerBoundaryIs></Polygon>", "37.390040,-122.081573", "http://maps.google.com/mapfiles/ms/icons/green.png"],
["John's Pizza", "no", "100 S Murphy Ave, Sunnyvale, CA", "<Polygon><outerBoundaryIs><LinearRing><coordinates>-122.047119,37.33113,0 -122.065315,37.332495,0 -122.077675,37.3385,0 -122.064285,37.378615,0 -122.036819,37.385162,0 -122.006607,37.382162,0 -122.00386,37.342048,0 -122.047119,37.331403,0 </coordinates></LinearRing></outerBoundaryIs></Polygon>", "37.377441,-122.030071", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
["John's Pizza", "no", "1200 Curtner Ave, San Jose, CA", "<Polygon><outerBoundaryIs><LinearRing><coordinates>-121.935196,37.345051,0 -121.931076,37.294267,0 -121.871338,37.293721,0 -121.806793,37.293174,0 -121.798553,37.361426,0 -121.879578,37.36088,0 -121.934509,37.345597,0 -121.935196,37.345051,0 </coordinates></LinearRing></outerBoundaryIs></Polygon>", "37.288742,-121.890765", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
["John's Pizza", "yes", "700 Blossom Hill Rd, San Jose, CA", "<Polygon><outerBoundaryIs><LinearRing><coordinates>-121.935883,37.253287,0 -121.931076,37.294267,0 -121.871338,37.293721,0 -121.806793,37.293174,0 -121.790657,37.234702,0 -121.852455,37.223221,0 -121.935539,37.253014,0 </coordinates></LinearRing></outerBoundaryIs></Polygon>", "37.250543,-121.846563", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
["John's Pizza", "yes", "100 N Milpitas Blvd, Milpitas, CA", "<Polygon><outerBoundaryIs><LinearRing><coordinates>-121.947556,37.435612,0 -121.934509,37.476493,0 -121.893311,37.469409,0 -121.852798,37.429615,0 -121.843872,37.400165,0 -121.887817,37.3898,0 -121.959915,37.420345,0 -121.959915,37.427979,0 -121.948929,37.435612,0 -121.947556,37.435612,0</coordinates></LinearRing></outerBoundaryIs></Polygon>", "37.434113,-121.901139", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
["John's Pizza", "yes", "3300 Mowry Blvd, Fremont, CA", "<Polygon><outerBoundaryIs><LinearRing><coordinates>-122.02343,37.52198,0 -122.023773,37.558731,0 -121.989784,37.573426,0 -121.959572,37.566351,0 -121.944466,37.544305,0 -121.967125,37.520891,0 -122.023087,37.522525,0</coordinates></LinearRing></outerBoundaryIs></Polygon>", "37.552773,-121.985153", "http://maps.google.com/mapfiles/ms/icons/blue.png"]
];
html,
body,
table,
tbody,
#map {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<table border="1" style="height: 90%; width:100%;">
<tr style="height: 100%; width:100%;">
<td style="height: 100%; width:100%;">
<div id="map"></div>
</td>
<td>
<div id="side_bar"></div>
</td>
</tr>
</table>
<input id="address" type="text" value="Palo Alto, CA" />
<input id="numberResults" type="text" value="5" />
<input type="button" value="Search" onclick="codeAddress();" />
<div id="info"></div>

Google Maps API: Get zipcode

One possible solution is to load all of your zipcode data into a table and then, when you need to get the zipcode with the nearest lat/long to the lat/long returned by Google Maps, use the Haversine formula in a query to get the distance between the lat/long from GoogleMaps and the lat/long of the zip codes. You can then select the zip code that is closest to the lat/long returned by Google Maps i.e. the one with the lowest distance from your point of interest.

Luckily there is just such a query in a previous post.

NB This will only give you the nearest zipcode in your list for a location. I do not know whether this means that you will get the correct zipcode for your location (I don't know enough about zipcodes for that!). It should give you something with which to get started though.

Find Nearest Bars From User's Postcode Using Google Maps API

You can find info on this particular feature of Google Maps API here:
https://developers.google.com/places/webservice/search

This web service lets you search with a keyword while specifying your position and a search radius, and returns a list of places matching those parameters in a json or xml document.

Your example would look like this:

https://maps.googleapis.com/maps/api/place/textsearch/json?key=your_api_key&query="bar"&location=lat,lon&radius=8000

You'll need to replace

  • your_api_key with the Google Maps API key for your application (you'll need one to use their web services)

  • lat,lon with the coordinates of the user, that you can find with the geocoding web service as user agmangas suggested

  • 8000 with the actual search radius, in meters (5 miles is about 8km).

Get directions to nearest marker maps javascript API

Your uLocation variable is a google.maps.LatLng object, it doesn't have a .position property (for that matter, the .position property of google.maps.Marker objects isn't documented, it would be safer to call the (documented) .getPosition() method on the markers)

var d = google.maps.geometry.spherical.computeDistanceBetween(
markers[i].position, uLocation.position);

should be:

var d = google.maps.geometry.spherical.computeDistanceBetween(
markers[i].getPosition(), uLocation);

related questions:

  • Google Maps API - Getting closest points to zipcode
  • Google Maps API - Closest marker function change to closest n markers

proof of concept fiddle

screenshot of map with closest marker result

code snippet:

jQuery(document).ready(function() {
// Create the script tag, set the appropriate attributes

let script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=places&libraries=geometry';
script.defer = true;
var map
let infowindow

window.initMap = function() {

const directionsRenderer = new google.maps.DirectionsRenderer();
const center = {
lat: -36.561551,
lng: -72.0954877
}
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: center
});
let markers = setMarkers(map)
directionsRenderer.setMap(map);
getDirections(markers, directionsRenderer)

}
const locations = [
['Super Pellet Santiago', -33.458717664930084, -70.77513497336462],
['Super Pellet Chillan', -36.561551, -72.0954877],
['Super Pellet Concepción', -36.8158124, -73.0741686],
['Super Pellet Los Angeles', -37.4774907, -72.3245759],
['Super Pellet Angol', -33.80010128657071, 151.28747820854187],
['Super Pellet Temuco', -38.7702088, -72.6301967]
];

function setMarkers(map) {
let markers = []
for (let i = 0; i < locations.length; i++) {
markers[i] = new google.maps.Marker({
title: locations[i][0],
position: {
lat: locations[i][1],
lng: locations[i][2]
},
map: map
});
google.maps.event.addListener(markers, 'click', (function(markers, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, markers);
}
})(markers, i));

}
return markers
// Append the 'script' element to 'head'
}
document.head.appendChild(script);

function getDirections(markers, directionsRenderer) {
let userLocation = {
lat: -32.8894587,
lng: -68.8458386
}; // Mendoza, Capital Department, Mendoza Province, Argentina (-32.8894587, -68.8458386)
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error)

function success(position) {
userLocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
}

function error() {
document.getElementById('output').innerHTML = "Debes activar la geolocalización<br>defaulting to:Mendoza, Capital Department, Mendoza Province, Argentina (-32.8894587, -68.8458386)";
}
}
//Get directions to nearest marker

jQuery('#FINDPOS').click(() => {
if (userLocation === 'undefined') {
alert("Debes permitir la localización")
} else {
let uLocation = new google.maps.LatLng(userLocation.lat, userLocation.lng);
let distances = [];
let closest = -1;
if (markers.length > 0) {
for (i = 0; i < markers.length; i++) {
var d = google.maps.geometry.spherical.computeDistanceBetween(markers[i].getPosition(), uLocation);
distances[i] = d;
if (closest == -1 || d < distances[closest]) {
closest = i;
}
}
document.getElementById('output').innerHTML = 'Closest marker is: ' + markers[closest].getTitle();
calculateAndDisplayRoute(uLocation, markers[closest].getPosition(), directionsRenderer);
}
}
})
}
})

function calculateAndDisplayRoute(start, end, directionsRenderer) {
const directionsService = new google.maps.DirectionsService();
directionsService.route({
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING,
},
(response, status) => {
if (status === "OK") {
directionsRenderer.setDirections(response);
} else {
window.alert("Directions request failed due to " + status);
}
}
);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */

#map {
height: 90%;
}

/* Optional: Makes the sample page fill the window. */

html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>

<body>
<input id="FINDPOS" value="FINDPOS" type="button" />
<div id="output"></div>
<div id="map"></div>
</body>

</html>


Related Topics



Leave a reply



Submit