How to add Google Maps Autocomplete search box? - javascript

I am trying to add a Google autocomplete search box to a website so that users can search for an address as easily as possible.
My problem is, I have looked a numerous questions on here as well as the Google Maps Javascript API v3 regarding this and some tutorials yet they all bundle together the autocomplete functionality with mapping it on an embedded Google map.
I don't need to map the location visually, I just need the autocomplete box for now, unfortunately I cannot work out which parts of the API are relevant to this and every example I have looked at includes plenty of JS for mapping.
How can I ONLY add the autocomplete input functionality?

A significant portion of this code can be eliminated.
HTML excerpt:
<head>
...
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
...
</head>
<body>
...
<input id="searchTextField" type="text" size="50">
...
</body>
Javascript:
function initialize() {
var input = document.getElementById('searchTextField');
new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);

To get latitude and longitude too, you can use this simple code:
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
<script>
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
document.getElementById('city2').value = place.name;
document.getElementById('cityLat').value = place.geometry.location.lat();
document.getElementById('cityLng').value = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />
<input type="hidden" id="city2" name="city2" />
<input type="hidden" id="cityLat" name="cityLat" />
<input type="hidden" id="cityLng" name="cityLng" />
</body>
</html>

To use Google Maps/Places APIs now, you're required to use an API Key. So the API URL will change from
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
to
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>

Just copy and paste the sameple code below.
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/jsvv=3.exp&sensor=false&libraries=places"></script>
</head>
<body>
<label for="locationTextField">Location</label>
<input id="locationTextField" type="text" size="50">
<script>
function init() {
var input = document.getElementById('locationTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', init);
</script>
</body>
</html>
Well formatted code can be found from this link.
http://jon.kim/how-to-add-google-maps-autocomplete-search-box/

So I've been playing around with this and it seems you need both places and js maps api activated. Then use the following:
HTML:
<input id="searchTextField" type="text" size="50">
<input id="address" name="address" value='' type="hidden" placeholder="">
JS:
<script>
function initMap() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
document.getElementById("address").value = JSON.stringify(place.address_components);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>

Use Google Maps JavaScript API with places library to implement Google Maps Autocomplete search box in the webpage.
HTML
<input id="searchInput" class="controls" type="text" placeholder="Enter a location">
JavaScript
<script>
function initMap() {
var input = document.getElementById('searchInput');
var autocomplete = new google.maps.places.Autocomplete(input);
}
</script>
Complete guide, source code, and live demo can be found from here - Google Maps Autocomplete Search Box with Map and Info Window

// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(poenter code heresition) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}

<input id="autocomplete" placeholder="Enter your address" type="text"/>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="https://mapenter code heres.googleapis.com/maps/api/js?key=AIzaSyC7vPqKI7qjaHCE1SPg6i_d1HWFv1BtODo&libraries=places"></script>
<script type="text/javascript">
function initialize() {
new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')), {
types: ['geocode']
});
}
initialize();
</script>

Follow the below code.
Add this to your TS file.
declare this, top of your class.
declare var google;
declare the view child for Map and the input.
#ViewChild('mapElement', {static: true}) mapNativeElement: ElementRef;
#ViewChild('autoCompleteInput', {static: true}) inputNativeElement: any;
this method is run on ngOnInit() event or ngAfterViewInit() event.
autoComplete() {
const map = new google.maps.Map(this.mapNativeElement.nativeElement, {
center: {lat: -33.8688, lng: 151.2093},
zoom: 7
});
const infowindow = new google.maps.InfoWindow();
const infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
const marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
const autocomplete = new google.maps.places.Autocomplete(this.inputNativeElement.nativeElement as HTMLInputElement);
autocomplete.addListener('place_changed', () => {
infowindow.close();
marker.setVisible(false);
const place = autocomplete.getPlace();
let cus_location = {
lat: place.geometry.location.lat(),
long: place.geometry.location.lng()
}
console.log('place data :................', cus_location);
localStorage.setItem('LOC_DATA', this.helper.encryptData(cus_location));
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert('No details available for input: ' + place.name );
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
let address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
if(infowindowContent){
infowindowContent.children['place-icon'].src = place.icon;
infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = address;
}
infowindow.open(map, marker);
});
}
calling the method on ngAfterViewInit.
ngAfterViewInit(): void {
this.autoComplete();
}
And this is the HTML code. please modify as per your need.
<ion-content fullscreen>
<div class="location-col">
<div class="google-map">
<!-- <img src="../../assets/images/google-map.jpg" alt=""> -->
<div #mapElement id="map"></div>
</div>
<div class="location-info">
<h2>Where is your car located?</h2>
<p>Enter address manually or click location detector icon to use current address.</p>
<div class="form-group">
<div class="location-row">
<input type="text" #autoCompleteInput class="location-input" [(ngModel)]="search_location" placeholder="Search location">
<span class="location-icon" (click)="getCurrentLocation()">
<img src="../../assets/images/location-icon.svg" alt="">
</span>
</div>
<button type="button" class="location-search-btn" (click)="goToVendorSearch()">
<i class="fa fa-angle-right"></i>
</button>
</div>
</div>
</div>
</ion-content>

I am currently using the Google API to retrieve the location that the user enters in the form/ input. I'm also using an angular function that showing the current location and suggests a city name pin code etc...
- add google API index.html.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxx&libraries=geometry,places"></script>
- add id in input box to get string & charcters.
<input id="autocomplete" type="text"(keydown)="checkAddress($event.target.value)">
- and create function on your component.ts file.
import these file
import * as _ from 'lodash';
declare var google: any;
checkAddress(value) {
if (!value) {
this.model.location = _.cloneDeep(value);
this.rfpForm.controls['location'].setValue(this.model.location);
}
}
initLocationAutocomplete() {
let autocomplete, place;
const getLocation = () => {
place = autocomplete.getPlace();
if (place && (place.formatted_address || place.name)) {
// if you want set value in your form controls like this
this.model.location = _.cloneDeep(place.formatted_address || place.name);
// YourFormName.controls['location'].setValue(this.model.location);
// YourFormName.controls['location']['_touched'] = true;
}
};
autocomplete = new google.maps.places.Autocomplete((document.getElementById('autocomplete')), { types: ['geocode'] });
autocomplete.addListener('place_changed', getLocation);
}

<input type="text"required id="autocomplete">
<script>
function initAutocomplete() {
new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),
{types: ['geocode']}
);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=&libraries=places&callback=initAutocomplete"
async defer></script>

<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete Address Form</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<script>
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initialize() {
// Create the autocomplete object, restricting the search
// to geographical location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {HTMLInputElement} */(document.getElementById('autocomplete')),
{ types: ['geocode'] });
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
}
// [START region_fillform]
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// [END region_fillform]
// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation]
</script>
<style>
#locationField, #controls {
position: relative;
width: 480px;
}
#autocomplete {
position: absolute;
top: 0px;
left: 0px;
width: 99%;
}
.label {
text-align: right;
font-weight: bold;
width: 100px;
color: #303030;
}
#address {
border: 1px solid #000090;
background-color: #f0f0ff;
width: 480px;
padding-right: 2px;
}
#address td {
font-size: 10pt;
}
.field {
width: 99%;
}
.slimField {
width: 80px;
}
.wideField {
width: 200px;
}
#locationField {
height: 20px;
margin-bottom: 2px;
}
</style>
</head>
<body onload="initialize()">
<div id="locationField">
<input id="autocomplete" placeholder="Enter your address"
onFocus="geolocate()" type="text"></input>
</div>
</body>
</html>

I am using jQuery here to get the entered text and wrapping all code in $(document).ready(). Make sure you have your API key ready for Google Places API Web service. Replace it in the below script file.
<input type="text" id="location">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_KEY_HERE]&libraries=places"></script>
<script src="javascripts/scripts.js"></scripts>
Use script file to load the autocomplete class. Your scripts.js file will look something like this.
// scripts.js custom js file
$(document).ready(function () {
google.maps.event.addDomListener(window, 'load', initialize);
});
function initialize() {
var input = document.getElementById('location');
var autocomplete = new google.maps.places.Autocomplete(input);
}

Related

How Do I Take An Input From A Textbox And Use It To Search For a Location On Google Maps?

I am working on a project and one of the goals is for the user to put a location's name into a textbox and press a button to search for a location on a Google map.
<h2>How to Use</h2>
<p>To use this program, enter a location then click the button to search for it.</p>
<h2>Search Location</h2>
Location: <input type="text" id="myText" value="">
<!-- This creates a textbox --->
<button onclick="searchFunction()">Search</button>
<!-- This creates a button --->
<p id="demo"></p>
<script>
function searchFunction() {
var location = document.getElementById("myText").value;
}
</script>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h1>Google Map</h1>
<div id="map"></div>
<script>
function initMap() {
var options = {
zoom: 12,
center: {
lat: 39.7684,
lng: -86.1581
}
}
var map = new google.maps.Map(document.getElementById('map'), options);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBhrDQVoc_0FJx4Hy4tsFMKtmX78VNTUhw&callback=initMap">
</script>
<script>
if (location == "Children's Museum") {
function initMap() {
var options = {
zoom: 12,
center: {
lat: 39.810230,
lng: -86.158882
}
}
var map = new google.maps.Map(document.getElementById('map'), options);
var locationTestPosition = {
lat: 39.810230,
lng: -86.158882
};
var marker = new google.maps.Marker({
position: locationTestPosition,
map: map
});
}
</script>
}
This is the code that I currently have. The idea is that the user will insert a place's name and then using an if/else statement, the code will place a marker on the map at the proper coordinates. I cannot seem to get it to work though. I am new to HTML and JavaScript, so this is a lot of learning for me.

GMaps API Places Autocomplete & Directions - Map is not initializing

So I'm fairly new to not only HTML but also working with API's. I've been working on implementing the Maps Javascript API, specifically the Places Autocomplete and Directions functionality.
Prior to this I simply initialized the map and it loaded properly every single time, but the moment I tried to (for testing purposes) implement the more complicated Places & Direction functionality it stopped initializing.
I browsed several forums and couldn't seem to find a solution to this problem. If anyone could point out a potential issue within the code I would be grateful!
Thanks!
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<!-- GMAIL CLIENT KEY: 462218843122-16riskqb5201tfaeh51nrjqo3bec7h1c.apps.googleusercontent.com -->
<!-- link to main stylesheet -->
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<!-- Navigation Bar -->
<div class="navbar">
Home
Sign In
Register
</div>
<!--
<div class="about">
<a>About</a><br />
<a>We use the Firebase API to create and manage user accounts.</a><br /><br />
<a>The user selects two travel points as displayed with the Google Maps API.</a><br /><br />
<a>We poll United/Uber/Amtrack APIs for the available travel options.</a><br /><br />
<a>We then email the user when a trip is available</a>
</div>
-->
<div class="destInt">
<a>Enter your Trip</a>
</div>
<div id="forms" style="position:absolute; top:30; left:0; height:50%; width: 50%">
<form>
<div id="mode-selector" class="controls">
<input type="radio" name="type" id="changemode-walking" checked="checked">
<label for="changemode-walking">Walking</label>
<input type="radio" name="type" id="changemode-transit">
<label for="changemode-transit">Transit</label>
<input type="radio" name="type" id="changemode-driving">
<label for="changemode-driving">Driving</label>
</div>
<input id="origin-input" class="controls" type="text"
placeholder="Enter an origin location"><br>
<input id="destination-input" class="controls" type="text"
placeholder="Enter a destination">
</form>
</div>
<!-- Map -->
<div id="map" style="position:absolute; top:35; right:0; height: 400px; width: 48%; margin-right: 12px"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 30.615, lng: -96.342},
zoom: 13
});
new AutocompleteDirectionsHandler(map);
}
/**
* #constructor
*/
function AutocompleteDirectionsHandler(map) {
this.map = map;
this.originPlaceId = null;
this.destinationPlaceId = null;
this.travelMode = 'WALKING';
var originInput = document.getElementById('origin-input');
var destinationInput = document.getElementById('destination-input');
var modeSelector = document.getElementById('mode-selector');
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
var originAutocomplete = new google.maps.places.Autocomplete(
originInput, {placeIdOnly: true});
var destinationAutocomplete = new google.maps.places.Autocomplete(
destinationInput, {placeIdOnly: true});
this.setupClickListener('changemode-walking', 'WALKING');
this.setupClickListener('changemode-transit', 'TRANSIT');
this.setupClickListener('changemode-driving', 'DRIVING');
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(originInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(destinationInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(modeSelector);
var geocoder = new google.maps.geocoder;
var service = new google.maps.DistanceMatrixService;
})
}
// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
var radioButton = document.getElementById(id);
var me = this;
radioButton.addEventListener('click', function() {
me.travelMode = mode;
me.route();
});
};
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
if (!place.place_id) {
window.alert("Please select an option from the dropdown list.");
return;
}
if (mode === 'ORIG') {
me.originPlaceId = place.place_id;
} else {
me.destinationPlaceId = place.place_id;
}
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=MY API KEY&libraries=places&callback=initMap">
</script>
<!-- End of Map -->
</body>
</html>
Your issue seems to be these lines:
// these lines are invalid
var geocoder = new google.maps.geocoder;
var service = new google.maps.DistanceMatrixService;
}) // this is not tied to anything
You have some extra brackets. You also have a couple lines of invalid code. If you want to invoke those constructors you need to call them ()

Google API Javascript, How to get the current location on IP-Address and on live site?

I wrote a code that works fine in JSFiddle, also at localhost, it is working fine. But when I move it to IP or on live site of Godaddy domain, it shows blank page! why?
Please Help me to get out of this problem. As I do google and spent a lot of time but not get any solution. Problem is with IP address and live server website. Please give me a solution if you know about this problem.
Here is the code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="//maps.googleapis.com/maps/api"></script>
<script src="scripts/jquery-3.2.1.min.js"></script>
<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyB3_ve60J0oE7IXz-LTuE0SqaWI8MWP9uQ&callback=requestPosition" ></script>
<script type="text/javascript">
function setText(val, e) {
document.getElementById(e).value = val;
}
function insertText(val, e) {
document.getElementById(e).value += val;
}
var nav = null;
function requestPosition() {
if (nav == null) {
nav = window.navigator;
}
if (nav != null) {
var geoloc = nav.geolocation;
if (geoloc != null) {
geoloc.getCurrentPosition(successCallback);
}
else {
alert("geolocation not supported");
}
}
else {
alert("Navigator not found");
}
}
function successCallback(position)
{
setText(position.coords.latitude, "latitude");
setText(position.coords.longitude, "longitude");
var latlng = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map124"), myOptions);
var marker = new google.maps.Marker
(
{
position: new google.maps.LatLng(position.coords.latitude,
position.coords.longitude),
map: map,
title: 'Click me'
}
);
}
</script>
</head>
<body>
<label for="latitude">Latitude: </label><input id="latitude" /> <br />
<label for="longitude">Longitude: </label><input id="longitude" /> <br />
<input type="button" onclick="requestPosition()" value="Get Latitude and Longitude" />
<div id="map124" style="width:400px;height:400px">
</div>
</body>
</html>

How to bind checkboxes to Google Maps markers using knockout.js?

I'm creating an app that renders a Google Map of a city, with location markers for nearby locations. I'm rendering these locations by requesting locations within an 800-unit radius to the google.maps.places.PlacesService API. In addition, I have a number of checkboxes representing the place types (e.g. park, museum, etc.). When these boxes are checked or unchecked, I'd like for the map to dynamically update and show or hide the corresponding map markers. I'm using the knockout.js framework to help with the implementation.
My checkboxes are knockout observables, and I've managed to create an array of the checkboxes that changes dynamically within the html. However, even though the array changes, the map itself does not, even though I have set the types variable to be my location that stores the results from the checkbox selection (data.Locations.arrLocations). How do I go about getting the correct bindings in this case?
I've included my index.html and app.js files below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<!-- This is a *view* - HTML markup that defines the appearance of your UI -->
<div id='searchBar'>
<p>Search: <strong data-bind="text: location"></strong></p>
<p><input type='checkbox' data-bind='checked: Locations' value='gym'> Gyms </p>
<p> <input type='checkbox' data-bind='checked: Locations' value='park'>Parks </p>
<p> <input type='checkbox' data-bind='checked: Locations' value='store'> Stores </p>
<p> <input type='checkbox' data-bind='checked: Locations' value='museum'> Museums </p>
<p> <input type='checkbox' data-bind='checked: Locations' value='zoo'> Zoos </p>
<p>Search: <input data-bind="value: location" /></p>
<div data-bind='text: ko.toJSON($data.Locations)'></div>
</div>
<div id='map'></div>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?signed_in=true&libraries=places&callback=initMap" async defer></script>
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-min.js'></script>
<script type='text/javascript' src='js/app.js'></script>
</body>
</html>
app.js:
var data = {
'Locations' : {
'arrLocations': ['park', 'gym']
}
};
function AppViewModel() {
this.location = ko.observable("Barcelona, Spain");
this.Locations = ko.observableArray(data.Locations.arrLocations);
}
var map;
var infowindow;
function initMap() {
var barcelona = {lat: 41.383, lng: 2.183};
map = new google.maps.Map(document.getElementById('map'), {
center: barcelona,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: barcelona,
radius: 800,
types: data.Locations.arrLocations,
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
You need to subscribe to changes in Locations and adjust your markers accordingly. To clear unwanted markers, you need to keep track of what markers you have added. I did this with a markers array. Each time Locations changes, all markers are removed, and then the search runs and adds markers.
viewModel.Locations.subscribe(function (newValue) {
console.debug("Changing", newValue);
for (var i=0; i<markers.length; ++i) {
markers[i].setMap(null);
}
markers = [];
service.nearbySearch({
location: barcelona,
radius: 800,
types: newValue
}, callback);
});
viewModel.Locations.notifySubscribers();
The notifySubscribers call causes the subscription to fire for the first run.
http://jsfiddle.net/53qfm5bz/1/

Centering a google map with javascript from pin

I have my page so that it allows the user to see their latitude and longitude. I've embedded a google map so that the user can click physically see where they're at. This is a project for my computer science class, so I don't want you to physically write the code for me. I just want suggestions on how to solve this. Here's what I have right now.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<!-- This page will allow the suer to track their location through means of the HTML5 Geolocation feature -->
<title>Assignment 4:Track My Location</title>
<meta name="author" content="Alan Sylvestre" />
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
function myLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locationReveal);
} else {
alert("Please use a different browser that supports geolocation.");
}
}
window.onload = myLocation;
function locationReveal(position) {
showMap(position.coords);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var div = document.getElementById("location");
div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
}
var map;
function showMap(coords) {
var googleLatAndLong = new google.maps.LatLng(coords.latitude, coords.longitude);
var mapOptions = {
zoom : 18,
center : googleLatAndLong,
mapTypeId : google.maps.MapTypeId.SATELLITE
};
var mapDiv = document.getElementById("map");
map = new google.maps.Map(mapDiv, mapOptions);
addMarker(googleLatAndLong);
}
google.maps.Map(mapDiv, mapOptions);
var marker;
function addMarker(latlong) {
var markerOptions = {
position : latlong,
map : map
};
marker = new google.maps.Marker(markerOptions);
}
var center;
function calculateCenter() {
center = map.getCenter();
}
</script>
</head>
<body style="background-color:yellow;" text="blue;">
<div align="center">
<h1>Reveal My Location</h1>
<p>
You know what's pretty cool? Tracking your location using a simple internet connection. By clicking this button, you're browser will track a global database and reveal your location in terms of latitude and longitude. Enjoy!
</p>
<div id="location"></div>
<br>
<div id="map" style="width:400px; height:400px;"></div>
<br>
<input type="button" id="centerOfMap" value="Center" onclick="calculateCenter()">
<footer>
<p>
© Copyright by Alan Sylvestre
</p>
</footer>
</div>
</body>
First you need to make sure that the DOM is loaded before you run your JavaScript.
That is why 'mapDiv' is 'undefined'.
Either wrap your script in a window.onload anonymous function or push it to just before the closing body tag.

Categories