-
Notifications
You must be signed in to change notification settings - Fork 887
/
Project_Code_12_FasterIsBetterPlacesAutocompletePart2.html
705 lines (657 loc) · 26.4 KB
/
Project_Code_12_FasterIsBetterPlacesAutocompletePart2.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
<!DOCTYPE html>
<html>
<head>
<style>
html,
body {
font-family: Arial, sans-serif;
height: 100%;
margin: 0;
padding: 0;
}
.container {
height: 100%;
position: relative;
}
input {
font-size: 12px;
}
h1 {
color: #525454;
font-size: 22px;
margin: 0 0 10px 0;
text-align: center;
}
#hide-listings,
#show-listings {
width: 48%;
}
hr {
background: #D0D7D9;
height: 1px;
margin: 20px 0 20px 0;
border: none;
}
#map {
bottom:0px;
height: 100%;
left: 362px;
position: absolute;
right: 0px;
}
.options-box {
background: #fff;
border: 1px solid #999;
border-radius: 3px;
height: 100%;
line-height: 35px;
padding: 10px 10px 30px 10px;
text-align: left;
width: 340px;
}
#pano {
width: 200px;
height: 200px;
}
#places-search,
#search-within-time-text {
width: 84%;
}
.text {
font-size: 12px;
}
#toggle-drawing {
width: 27%;
position: relative;
margin-left: 10px;
}
#zoom-to-area-text {
width: 70%;
}
#zoom-to-area {
width: 24%;
}
</style>
</head>
<body>
<div class="container">
<div class="options-box">
<h1>Find Your New NYC Home</h1>
<div>
<input id="show-listings" type="button" value="Show Listings">
<input id="hide-listings" type="button" value="Hide Listings">
<hr>
<span class="text"> Draw a shape to search within it for homes!</span>
<input id="toggle-drawing" type="button" value="Drawing Tools">
</div>
<hr>
<div>
<input id="zoom-to-area-text" type="text" placeholder="Enter your favorite area!">
<input id="zoom-to-area" type="button" value="Zoom">
</div>
<hr>
<div>
<span class="text"> Within </span>
<select id="max-duration">
<option value="10">10 min</option>
<option value="15">15 min</option>
<option value="30">30 min</option>
<option value="60">1 hour</option>
</select>
<select id="mode">
<option value="DRIVING">drive</option>
<option value="WALKING">walk</option>
<option value="BICYCLING">bike</option>
<option value="TRANSIT">transit ride</option>
</select>
<span class="text">of</span>
<input id="search-within-time-text" type="text" placeholder="Ex: Google Office NYC or 75 9th Ave, New York, NY">
<input id="search-within-time" type="button" value="Go">
</div>
<hr>
<div>
<span class="text">Search for nearby places</span>
<input id="places-search" type="text" placeholder="Ex: Pizza delivery in NYC">
<input id="go-places" type="button" value="Go">
</div>
</div>
<div id="map"></div>
</div>
<script>
var map;
// Create a new blank array for all the listing markers.
var markers = [];
// This global polygon variable is to ensure only ONE polygon is rendered.
var polygon = null;
// Create placemarkers array to use in multiple functions to have control
// over the number of places that show.
var placeMarkers = [];
function initMap() {
// Create a styles array to use with the map.
var styles = [
{
featureType: 'water',
stylers: [
{ color: '#19a0d8' }
]
},{
featureType: 'administrative',
elementType: 'labels.text.stroke',
stylers: [
{ color: '#ffffff' },
{ weight: 6 }
]
},{
featureType: 'administrative',
elementType: 'labels.text.fill',
stylers: [
{ color: '#e85113' }
]
},{
featureType: 'road.highway',
elementType: 'geometry.stroke',
stylers: [
{ color: '#efe9e4' },
{ lightness: -40 }
]
},{
featureType: 'transit.station',
stylers: [
{ weight: 9 },
{ hue: '#e85113' }
]
},{
featureType: 'road.highway',
elementType: 'labels.icon',
stylers: [
{ visibility: 'off' }
]
},{
featureType: 'water',
elementType: 'labels.text.stroke',
stylers: [
{ lightness: 100 }
]
},{
featureType: 'water',
elementType: 'labels.text.fill',
stylers: [
{ lightness: -100 }
]
},{
featureType: 'poi',
elementType: 'geometry',
stylers: [
{ visibility: 'on' },
{ color: '#f0e4d3' }
]
},{
featureType: 'road.highway',
elementType: 'geometry.fill',
stylers: [
{ color: '#efe9e4' },
{ lightness: -25 }
]
}
];
// Constructor creates a new map - only center and zoom are required.
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.7413549, lng: -73.9980244},
zoom: 13,
styles: styles,
mapTypeControl: false
});
// This autocomplete is for use in the search within time entry box.
var timeAutocomplete = new google.maps.places.Autocomplete(
document.getElementById('search-within-time-text'));
// This autocomplete is for use in the geocoder entry box.
var zoomAutocomplete = new google.maps.places.Autocomplete(
document.getElementById('zoom-to-area-text'));
// Bias the boundaries within the map for the zoom to area text.
zoomAutocomplete.bindTo('bounds', map);
// Create a searchbox in order to execute a places search
var searchBox = new google.maps.places.SearchBox(
document.getElementById('places-search'));
// Bias the searchbox to within the bounds of the map.
searchBox.setBounds(map.getBounds());
// These are the real estate listings that will be shown to the user.
// Normally we'd have these in a database instead.
var locations = [
{title: 'Park Ave Penthouse', location: {lat: 40.7713024, lng: -73.9632393}},
{title: 'Chelsea Loft', location: {lat: 40.7444883, lng: -73.9949465}},
{title: 'Union Square Open Floor Plan', location: {lat: 40.7347062, lng: -73.9895759}},
{title: 'East Village Hip Studio', location: {lat: 40.7281777, lng: -73.984377}},
{title: 'TriBeCa Artsy Bachelor Pad', location: {lat: 40.7195264, lng: -74.0089934}},
{title: 'Chinatown Homey Space', location: {lat: 40.7180628, lng: -73.9961237}}
];
var largeInfowindow = new google.maps.InfoWindow();
// Initialize the drawing manager.
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_LEFT,
drawingModes: [
google.maps.drawing.OverlayType.POLYGON
]
}
});
// Style the markers a bit. This will be our listing marker icon.
var defaultIcon = makeMarkerIcon('0091ff');
// Create a "highlighted location" marker color for when the user
// mouses over the marker.
var highlightedIcon = makeMarkerIcon('FFFF24');
// The following group uses the location array to create an array of markers on initialize.
for (var i = 0; i < locations.length; i++) {
// Get the position from the location array.
var position = locations[i].location;
var title = locations[i].title;
// Create a marker per location, and put into markers array.
var marker = new google.maps.Marker({
position: position,
title: title,
animation: google.maps.Animation.DROP,
icon: defaultIcon,
id: i
});
// Push the marker to our array of markers.
markers.push(marker);
// Create an onclick event to open the large infowindow at each marker.
marker.addListener('click', function() {
populateInfoWindow(this, largeInfowindow);
});
// Two event listeners - one for mouseover, one for mouseout,
// to change the colors back and forth.
marker.addListener('mouseover', function() {
this.setIcon(highlightedIcon);
});
marker.addListener('mouseout', function() {
this.setIcon(defaultIcon);
});
}
document.getElementById('show-listings').addEventListener('click', showListings);
document.getElementById('hide-listings').addEventListener('click', function() {
hideMarkers(markers);
});
document.getElementById('toggle-drawing').addEventListener('click', function() {
toggleDrawing(drawingManager);
});
document.getElementById('zoom-to-area').addEventListener('click', function() {
zoomToArea();
});
document.getElementById('search-within-time').addEventListener('click', function() {
searchWithinTime();
});
// Listen for the event fired when the user selects a prediction from the
// picklist and retrieve more details for that place.
searchBox.addListener('places_changed', function() {
searchBoxPlaces(this);
});
// Listen for the event fired when the user selects a prediction and clicks
// "go" more details for that place.
document.getElementById('go-places').addEventListener('click', textSearchPlaces);
// Add an event listener so that the polygon is captured, call the
// searchWithinPolygon function. This will show the markers in the polygon,
// and hide any outside of it.
drawingManager.addListener('overlaycomplete', function(event) {
// First, check if there is an existing polygon.
// If there is, get rid of it and remove the markers
if (polygon) {
polygon.setMap(null);
hideMarkers(markers);
}
// Switching the drawing mode to the HAND (i.e., no longer drawing).
drawingManager.setDrawingMode(null);
// Creating a new editable polygon from the overlay.
polygon = event.overlay;
polygon.setEditable(true);
// Searching within the polygon.
searchWithinPolygon(polygon);
// Make sure the search is re-done if the poly is changed.
polygon.getPath().addListener('set_at', searchWithinPolygon);
polygon.getPath().addListener('insert_at', searchWithinPolygon);
});
}
// This function populates the infowindow when the marker is clicked. We'll only allow
// one infowindow which will open at the marker that is clicked, and populate based
// on that markers position.
function populateInfoWindow(marker, infowindow) {
// Check to make sure the infowindow is not already opened on this marker.
if (infowindow.marker != marker) {
// Clear the infowindow content to give the streetview time to load.
infowindow.setContent('');
infowindow.marker = marker;
// Make sure the marker property is cleared if the infowindow is closed.
infowindow.addListener('closeclick', function() {
infowindow.marker = null;
});
var streetViewService = new google.maps.StreetViewService();
var radius = 50;
// In case the status is OK, which means the pano was found, compute the
// position of the streetview image, then calculate the heading, then get a
// panorama from that and set the options
function getStreetView(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
var nearStreetViewLocation = data.location.latLng;
var heading = google.maps.geometry.spherical.computeHeading(
nearStreetViewLocation, marker.position);
infowindow.setContent('<div>' + marker.title + '</div><div id="pano"></div>');
var panoramaOptions = {
position: nearStreetViewLocation,
pov: {
heading: heading,
pitch: 30
}
};
var panorama = new google.maps.StreetViewPanorama(
document.getElementById('pano'), panoramaOptions);
} else {
infowindow.setContent('<div>' + marker.title + '</div>' +
'<div>No Street View Found</div>');
}
}
// Use streetview service to get the closest streetview image within
// 50 meters of the markers position
streetViewService.getPanoramaByLocation(marker.position, radius, getStreetView);
// Open the infowindow on the correct marker.
infowindow.open(map, marker);
}
}
// This function will loop through the markers array and display them all.
function showListings() {
var bounds = new google.maps.LatLngBounds();
// Extend the boundaries of the map for each marker and display the marker
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
bounds.extend(markers[i].position);
}
map.fitBounds(bounds);
}
// This function will loop through the listings and hide them all.
function hideMarkers(markers) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
// This function takes in a COLOR, and then creates a new marker
// icon of that color. The icon will be 21 px wide by 34 high, have an origin
// of 0, 0 and be anchored at 10, 34).
function makeMarkerIcon(markerColor) {
var markerImage = new google.maps.MarkerImage(
'http://chart.googleapis.com/chart?chst=d_map_spin&chld=1.15|0|'+ markerColor +
'|40|_|%E2%80%A2',
new google.maps.Size(21, 34),
new google.maps.Point(0, 0),
new google.maps.Point(10, 34),
new google.maps.Size(21,34));
return markerImage;
}
// This shows and hides (respectively) the drawing options.
function toggleDrawing(drawingManager) {
if (drawingManager.map) {
drawingManager.setMap(null);
// In case the user drew anything, get rid of the polygon
if (polygon !== null) {
polygon.setMap(null);
}
} else {
drawingManager.setMap(map);
}
}
// This function hides all markers outside the polygon,
// and shows only the ones within it. This is so that the
// user can specify an exact area of search.
function searchWithinPolygon() {
for (var i = 0; i < markers.length; i++) {
if (google.maps.geometry.poly.containsLocation(markers[i].position, polygon)) {
markers[i].setMap(map);
} else {
markers[i].setMap(null);
}
}
}
// This function takes the input value in the find nearby area text input
// locates it, and then zooms into that area. This is so that the user can
// show all listings, then decide to focus on one area of the map.
function zoomToArea() {
// Initialize the geocoder.
var geocoder = new google.maps.Geocoder();
// Get the address or place that the user entered.
var address = document.getElementById('zoom-to-area-text').value;
// Make sure the address isn't blank.
if (address == '') {
window.alert('You must enter an area, or address.');
} else {
// Geocode the address/area entered to get the center. Then, center the map
// on it and zoom in
geocoder.geocode(
{ address: address,
componentRestrictions: {locality: 'New York'}
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.setZoom(15);
} else {
window.alert('We could not find that location - try entering a more' +
' specific place.');
}
});
}
}
// This function allows the user to input a desired travel time, in
// minutes, and a travel mode, and a location - and only show the listings
// that are within that travel time (via that travel mode) of the location
function searchWithinTime() {
// Initialize the distance matrix service.
var distanceMatrixService = new google.maps.DistanceMatrixService;
var address = document.getElementById('search-within-time-text').value;
// Check to make sure the place entered isn't blank.
if (address == '') {
window.alert('You must enter an address.');
} else {
hideMarkers(markers);
// Use the distance matrix service to calculate the duration of the
// routes between all our markers, and the destination address entered
// by the user. Then put all the origins into an origin matrix.
var origins = [];
for (var i = 0; i < markers.length; i++) {
origins[i] = markers[i].position;
}
var destination = address;
var mode = document.getElementById('mode').value;
// Now that both the origins and destination are defined, get all the
// info for the distances between them.
distanceMatrixService.getDistanceMatrix({
origins: origins,
destinations: [destination],
travelMode: google.maps.TravelMode[mode],
unitSystem: google.maps.UnitSystem.IMPERIAL,
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
window.alert('Error was: ' + status);
} else {
displayMarkersWithinTime(response);
}
});
}
}
// This function will go through each of the results, and,
// if the distance is LESS than the value in the picker, show it on the map.
function displayMarkersWithinTime(response) {
var maxDuration = document.getElementById('max-duration').value;
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
// Parse through the results, and get the distance and duration of each.
// Because there might be multiple origins and destinations we have a nested loop
// Then, make sure at least 1 result was found.
var atLeastOne = false;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
if (element.status === "OK") {
// The distance is returned in feet, but the TEXT is in miles. If we wanted to switch
// the function to show markers within a user-entered DISTANCE, we would need the
// value for distance, but for now we only need the text.
var distanceText = element.distance.text;
// Duration value is given in seconds so we make it MINUTES. We need both the value
// and the text.
var duration = element.duration.value / 60;
var durationText = element.duration.text;
if (duration <= maxDuration) {
//the origin [i] should = the markers[i]
markers[i].setMap(map);
atLeastOne = true;
// Create a mini infowindow to open immediately and contain the
// distance and duration
var infowindow = new google.maps.InfoWindow({
content: durationText + ' away, ' + distanceText +
'<div><input type=\"button\" value=\"View Route\" onclick =' +
'\"displayDirections("' + origins[i] + '");\"></input></div>'
});
infowindow.open(map, markers[i]);
// Put this in so that this small window closes if the user clicks
// the marker, when the big infowindow opens
markers[i].infowindow = infowindow;
google.maps.event.addListener(markers[i], 'click', function() {
this.infowindow.close();
});
}
}
}
}
if (!atLeastOne) {
window.alert('We could not find any locations within that distance!');
}
}
// This function is in response to the user seelecting "show route" on one
// of the markers within the desired commute. This will display the route
// on the map.
function displayDirections(origin) {
hideMarkers(markers);
var directionsService = new google.maps.DirectionsService;
// Get the destination address from the user entered value.
var destinationAddress =
document.getElementById('search-within-time-text').value;
// Get mode again from the user entered value.
var mode = document.getElementById('mode').value;
directionsService.route({
// The origin is the passed in marker's position.
origin: origin,
// The destination is user entered address.
destination: destinationAddress,
travelMode: google.maps.TravelMode[mode]
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
directions: response,
draggable: true,
polylineOptions: {
strokeColor: 'green'
}
});
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
// This function is in response to the user selecting "show route" on one
// of the markers within the calculated distance. This will display the route
// on the map.
function displayDirections(origin) {
hideMarkers(markers);
var directionsService = new google.maps.DirectionsService;
// Get the destination address from the user entered value.
var destinationAddress =
document.getElementById('search-within-time-text').value;
// Get mode again from the user entered value.
var mode = document.getElementById('mode').value;
directionsService.route({
// The origin is the passed in marker's position.
origin: origin,
// The destination is user entered address.
destination: destinationAddress,
travelMode: google.maps.TravelMode[mode]
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
directions: response,
draggable: true,
polylineOptions: {
strokeColor: 'green'
}
});
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
// This function fires when the user selects a searchbox picklist item.
// It will do a nearby search using the selected query string or place.
function searchBoxPlaces(searchBox) {
hideMarkers(placeMarkers);
var places = searchBox.getPlaces();
// For each place, get the icon, name and location.
createMarkersForPlaces(places);
if (places.length == 0) {
window.alert('We did not find any places matching that search!');
}
}
// This function firest when the user select "go" on the places search.
// It will do a nearby search using the entered query string or place.
function textSearchPlaces() {
var bounds = map.getBounds();
hideMarkers(placeMarkers);
var placesService = new google.maps.places.PlacesService(map);
placesService.textSearch({
query: document.getElementById('places-search').value,
bounds: bounds
}, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
createMarkersForPlaces(results);
}
});
}
// This function creates markers for each place found in either places search.
function createMarkersForPlaces(places) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < places.length; i++) {
var place = places[i];
var icon = {
url: place.icon,
size: new google.maps.Size(35, 35),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(15, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location,
id: place.id
});
// If a marker is clicked, do a place details search on it in the next function.
marker.addListener('click', function() {
getPlacesDetails(this, place);
});
placeMarkers.push(marker);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
}
map.fitBounds(bounds);
}
</script>
<script async defer
src=
"https://maps.googleapis.com/maps/api/js?libraries=places,geometry,drawing&key=MYAPIKEY&v=3&callback=initMap">
</script>
</body>
</html>