GMaps API Places Autocomplete & Directions - Map is not initializing - javascript

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 ()

Related

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 do you autocomplete location search when using the Mapbox API with Angular JS?

I am currently using the Mapbox API to retrieve the location that the user enters in the form. I'm also using the leaflet-angular-directive that allows me to render my map with the attributes that are attached to my '$scope'.
While I can retrieve a location and post a pin to my map after the user submits, I can't figure out how to autocomplete the search results similar to this example.
Here is a snippet from my controller. The &autocomplete=true in my API endpoint does not work.
function CreateController ($http, $scope) {
var vm = this;
vm.new_location = {};
vm.locations = [];
vm.submitLocationForm = function(){
vm.geocode(vm.addPin);
}
//GET LOCATION FROM QUERY
vm.geocode = function(addMapData) {
//api from mapbox with access token
var apiEndpoint = 'https://api.mapbox.com/geocoding/v5/mapbox.places/'+vm.new_location.locationName+'.json?access_token=' + MY_API_KEY + '&autocomplete=true'
//ajax call to get location data from the zipcode
$http.get(apiEndpoint)
.then(function(mapData) {
var coordinates = mapData.data.features[0].center; //array [long, lat]
addMapData(coordinates);// callback function that is called only after http call is receives data
})
}
angular.extend($scope, {
center: {
autoDiscover: true
},
markers: {
}, //markers is empty b/c users will add markers
defaults: {
// minZoom: 2,
// doubleClickZoom: true,
markerZoomAnimation: true
}
);
//adding pin
vm.addPin = function(coordinates){
vm.pinCounter += 1;
vm.new_location.pinOrder = vm.pinCounter;
vm.new_location.longitude = coordinates[0];
vm.new_location.latitude = coordinates[1];
$scope.markers[vm.pinCounter] = {
lat: vm.new_location.latitude,
lng: vm.new_location.longitude,
message: vm.new_location.textContent,
draggable: false,
focus: true,
riseOnHover: true,
zoom: 10
}
}
Here's the HTML for the form:
<form ng-submit="CreateController.submitLocationForm()">
<div class="form-group">
<input type="text" ng-model="CreateController.new_location.locationName" class="form-control" placeholder="Location name" autofocus>
</div>
<input type="submit" value="Submit" class="btn btn-block btn-info">
</form>
This is the code that's available on the Mapbox documentation, but I'm unsure how to modify it in order to use it with Angular:
<html>
<head>
<meta charset=utf-8 />
<title>Geocoding with autocomplete</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.mapbox.com/mapbox.js/v2.4.0/mapbox.js'></script>
<link href='https://api.mapbox.com/mapbox.js/v2.4.0/mapbox.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map'></div>
<script>
L.mapbox.accessToken = '<your access token here>';
L.mapbox.map('map', 'mapbox.streets')
.addControl(L.mapbox.geocoderControl('mapbox.places', {
autocomplete: true
}));
</script>
</body>
</html>
You seem to be looking at our old Mapbox JS library. A newer one has been released that makes maps much more fluid. The documentation has a geocoder example with autocomplete, i'd recommend looking over. If you have any additional question, i'll be glad to answer them.

Call two JavaScript functions from one button

I'm trying to execute two separate functions from one onClick.
It is a dictionary service which returns definitions from Glosbi API and the second function is Google Maps API call that changes the map to what has been searched for.
The first functions works perfectly, but the second function calling Google Maps API doesn't work.
Can anyone see anything in my code that isn't right or needs to be changed? I feel very close!
function codeTerm() {
$(document).ready(function(){
$('#term').focus(function(){
var full = $("#definition").has("definition").length ? true : false;
if(full === false){
$('#definition').empty();
}
});
var getDefinition = function(){
var word = $('#term').val();
if(word === ''){
$('#definition').html("<h2 class='loading'>We haven't forgotten to validate the form! Please enter a word.</h2>");
}
else {
$('#definition').html("<h2 class='loading'>Your definition is on its way!</h2>");
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=" +word+ "&pretty=true&callback=?", function(json) {
if (json !== "No definition has been found."){
var meanings = "";
json["tuc"].forEach(function(tuc) {
if (typeof tuc["meanings"] !== 'undefined') {
tuc["meanings"].forEach(function(m) {
meanings += "<p>"+m["text"]+"</p>\n";
});
}
});
$("#definition").html(meanings);
}
else {
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=&pretty=true" + "?callback=?", function(json) {
console.log(json);
$('#definition').html('<h2 class="loading">Nothing found.</h2><img id="thedefinition" src=' + json.definition[0].image.url + ' />');
});
}
});
}
return false;
};
$('#search').click(getDefinition);
$('#term').keyup(function(event){
if(event.keyCode === 13){
getDefinition();
}
});
});
}
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var country = document.getElementById('search').value;
geocoder.geocode( { 'search': country}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
$('#search').click(country);
$('#term').keyup(function(results){
if(results.keyCode === 13){
country();
}
});
And the HTML
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="author" content="Matthew Hughes">
<meta name="Dictionary" content="A dictionary web service">
<title>Dictionary Web Application</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="dictionary.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCVD1Kaf1yE4M9IcBNRAyujObcY2sGI0J0&sensor=false"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="dictionary.js"></script>
</head>
<body>
<div id="container">
<div id="top">
<header>
<h1>Dictionary Application</h1>
</header>
</div>
<div id="app">
<div id="panel">
<input id="term" type="text" placeholder="Enter a word...">
<button id="search" onclick="codeTerm(); codeAddress();">Define!</button>
</div>
<section id="definition">
</section>
<div id="map-canvas">
</div>
</div>
<footer>
<p>Created by Matthew Hughes</p>
</footer>
</div>
</body>
Thanks!
In the comments you mention 2 errors...
google is not defined
Was the inclusion of the Google API successful? You have this:
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCVD1Kaf1yE4M9IcBNRAyujObcY2sGI0J0&sensor=false"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
Do those references work? In your browser debugging tools, take a look at the network tab. What do these calls return, if anything? It sounds like the API isn't being loaded successfully. Do you need those to be https specifically? Try omitting the protocol so that it defaults to the current page's protocol:
<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyCVD1Kaf1yE4M9IcBNRAyujObcY2sGI0J0&sensor=false"></script>
<script src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
You're also including one of your JavaScript libraries twice:
<script src="dictionary.js"></script>
That might not break anything, but it also might. In any event, it should only be included once.
country if not defined
You create a variable called country in one of your functions:
function codeAddress() {
var country = document.getElementById('search').value;
// other code
}
So it's scope is within that function only. But you also try to reference it outside of that function, and you try to reference it as a function:
$('#search').click(country);
$('#term').keyup(function(results){
if(results.keyCode === 13){
country();
}
});
So even if it were moved to a global scope, country isn't a function so it's not clear what you're trying to accomplish with these two handlers. Maybe you meant to invoke a different function?

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.

How to add Google Maps Autocomplete search box?

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);
}

Categories