Google Maps API v3 load array of locations, detect ip and zoom, generate list by distance to locations

In the template or HTML:

<div id="container">
<div class="row mapSubNav">
<div class="col-xs-6">
<div class="mapNavLeft">Find a Store</div>
</div>
<div class="col-xs-6 mapNavRight">
<a id="mapView">Map View</a> | <a id="listView">List View</a>
</div>
</div>
<div class="row">
<div class="col-xs-12 noPad">
<div id="floating-panel">
<input id="findAddress" name="findAddress" type="textbox" value="Find a StoreĀ - City, State, Zip">
<select id="findRadius">
<option value="13" selected="selected">radius</option>
<option value="12">5 miles</option> <!-- 4 miles -->
<option value="11">10 miles</option> <!-- 8 miles -->
<option value="10">15 miles</option> <!-- 16 miles -->
</select>
<input id="findSubmit" type="submit" value="Find a shop" class="btnLeft">
</div>
<div class="sideBar">
<div class="closeBtn">x</div>
<h3>Our Stores:</h3>
</div>
<div id="map"></div>
<div id="outputList"></div>
</div>
</div>
</div><strong>
</strong>

<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&amp;amp;key=**YOUR_KEY_HERE**"</script>;
<script type="text/javascript" src="${sharedResourcePath}/js/locations.js"</script>;
<script type="text/javascript" src="${sharedResourcePath}/js/maps-module.js"</script>;

Locations array example:

var DEALERS = (function() {
var image = '../images/marker.png';

var locations = [
['location name 1',32.215143,-90.151818,map,image,'detailed description'],
['location name 2',47.336401,-116.888100,map,image,'detailed description'],
['location name 3',33.755219,-90.715672,map,image,'detailed description'],
['location name 4',33.646063,-87.058802,map,image,'detailed description'],
['location name 5',48.548468,-117.909399,map,image,'detailed description']
];
})();

 

MAPS MODULE JS:

MAPMOD = (function( window, google, DEALERS ) {

 var gmarkers = [],
 infos = [],
 map = {},
 whichMap = "";

 var init = (function init () {
 
 if( !document.getElementById("map") ) { return; }

 whichMap = $('#map').attr("data-map-type");

 switch( whichMap ) {
 case "dealer":
 var myOptions = {
 //center: new google.maps.LatLng(37.4419, -122.1419),
 zoom: 4,
 mapTypeId: google.maps.MapTypeId.ROADMAP,
 scrollwheel: false,
 disableDefaultUI: true,
 draggable: false,
 scaleControl: false,
 zoomControl: false
 };
 initDealerDetail(myOptions);
 break;

 case "all": 
 var myOptions = {
 zoom: 4,
 mapTypeId: google.maps.MapTypeId.ROADMAP,
 scrollwheel: false
 };
 allDealers(myOptions);
 break;
 }
 });

 var allDealers = (function allDealers (myOptions) {
 
 map = new google.maps.Map( document.getElementById("map"), myOptions );

 setMarkers( map, DEALERS.locations );

 var geocoder = new google.maps.Geocoder();

 var US = {
 NorthEast: {
 lat: 49.38,
 lng: -66.94
 },
 SouthWest: {
 lat: 25.82,
 lng: -124.39
 }
 }
 
 var USbounds = new google.maps.LatLngBounds(new google.maps.LatLng(US.SouthWest.lat, US.SouthWest.lng),
 new google.maps.LatLng(US.NorthEast.lat, US.NorthEast.lng));

 map.fitBounds(USbounds);
 //var USrect = new google.maps.Rectangle({map:map, bounds: USbounds});

 $('#findSubmit').on('click', function() {
 geocodeAddress(geocoder, map);
 });

 $("#findAddress").on("click", function() {
 $(this).val("");
 })

 $("#mapView").on("click", function() {
 $("#outputList").hide();
 $("#map").show();
 })
 
 $("#listView").on("click", function() {
 $("#map").hide();
 $("#outputList").show();
 })
 
 document.onkeydown=function() {
 if(window.event.keyCode=='13') {
 $('#findSubmit').click();
 }
 }

 geolocate(geocoder, map);
 });

 var geolocate = (function geolocate (geocoder, map) {

 // Try HTML5 geolocation.
 if (navigator.geolocation) {

 //var address = document.getElementById('findAddress').value ? document.getElementById('findAddress').value : {};

 navigator.geolocation.getCurrentPosition(function(position) {
 var pos = {
 lat: position.coords.latitude,
 lng: position.coords.longitude
 };

 //infoWindow.setPosition(pos);
 //infoWindow.setContent('Location found.');
 document.getElementById('findAddress').value = pos.lat + " " + pos.lng;
 $('#findRadius').val(8);
 geocodeAddress(geocoder, map);

 //map.setCenter(pos);
 //map.setZoom(9);
 }, function() {
 handleLocationError(true, infoWindow, map.getCenter());
 });
 } else {
 // Browser doesn't support Geolocation
 handleLocationError(false, infoWindow, map.getCenter());
 }
 });

 var initDealerDetail = (function initDealerDetail (myOptions) {

 map = new google.maps.Map( document.getElementById("map"), myOptions );

 setMarkers( map, DEALERS.locations );

 var lat = parseFloat( $('#map').attr("data-map-lat") );
 var lng = parseFloat( $('#map').attr("data-map-lng") );

 var pos = {
 lat: lat,
 lng: lng
 };

 map.setCenter(pos);
 map.setZoom(15);
 map.panBy(-250, 0);
 });
 
 function handleLocationError(browserHasGeolocation, map, pos) {
 map.setPosition(pos);
 map.setContent(browserHasGeolocation ? 'Error: The Geolocation service failed.' : 'Error: Your browser doesn\'t support geolocation.');
 }
 
 function geocodeAddress(geocoder, resultsMap) {
 
 var address = document.getElementById('findAddress').value;
 
 var radius = parseInt($( "#findRadius option:selected" ).val());
 if(isNaN(radius)){ radius = 8; }

 geocoder.geocode({'address': address}, function(results, status) {
 
 if (status === google.maps.GeocoderStatus.OK) {
 resultsMap.setCenter(results[0].geometry.location);

 var marker = new google.maps.Marker({
 map: resultsMap,
 position: results[0].geometry.location,
 });

 closest = findClosestN(results[0].geometry.location,10);

 // get driving distance
 closest = closest.splice(0,10);
 $('#findAddress').val(results[0].formatted_address);

 calculateDistances(results[0].geometry.location, closest,10);
 
 resultsMap.setZoom(radius);
 
 } else {
 $('#findAddress').val("No results. Please try again");
 }
 });
 }
 
 function findClosestN(pt,numberOfResults) {
 var closest = [];

 for (var i=0; i<gmarkers.length;i++) {
 gmarkers[i].distance = google.maps.geometry.spherical.computeDistanceBetween(pt,gmarkers[i].getPosition());
 
 //$('#findAddress').val("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) {
 $('#outputList').html('');
 var service = new google.maps.DistanceMatrixService();
 var request = {
 origins: [pt],
 destinations: [],
 travelMode: google.maps.TravelMode.DRIVING,
 unitSystem: google.maps.UnitSystem.IMPERIAL,
 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 results = response.rows[0].elements;
 for (var i = 0; i < numberOfResults; i++) {

 $('#outputList').append('\
 <label for="dealer' + i + '" class="col-xs-8 dealerItem">\
 <input type="radio" value="' + closest[i].title + '" name="dealers" id="dealer' + i + '">\
 <span>' + closest[i].title + '</span>\
 <span class="dealerAddress">' + destinations[i] + '</span>\
 </label>\
 <div class="col-xs-4 distance">' + results[i].distance.text + '</div>');
 }
 }
 });
 }
 
 function setMarkers(map,locations) {
 
 var marker, i
 
 for (i = 0; i < locations.length; i++) { 
 
 var loan = locations[i][0],
 lat = locations[i][1],
 lng = locations[i][2],
 add = locations[i][5];
 
 latlngset = new google.maps.LatLng(lat, lng);

 var marker = new google.maps.Marker({ 
 map: map,
 title: loan ,
 position: latlngset,
 icon: './images/tp.png'
 });

 gmarkers.push(marker);
 
 //console.log(marker.getPosition());
 //map.setCenter(marker.getPosition());
 
 var content = add;
 var infowindow = new google.maps.InfoWindow();
 
 google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){ 
 
 return function() {
 
 /* close the previous info-window */
 closeInfos();
 
 infowindow.setContent(content);
 infowindow.open(map,marker);
 
 /* keep the handle, in order to close it on next click event */
 infos[0]=infowindow;
 
 };

 })(marker,content,infowindow)); 
 
 }
 }
 
 function closeInfos() {
 
 if(infos.length > 0) {
 
 /* detach the info-window from the marker ... undocumented in the API docs */
 infos[0].set("marker", null);
 
 /* and close it */
 infos[0].close();
 
 /* blank the array */
 infos.length = 0;
 }
 }
 
 return {
 init: init
 }

})(window, google, window.DEALERS);
MAPMOD.initMap();

Leave a Reply

You must be logged in to post a comment.