jquery and google places autocomplete - javascript

I would like to add the Google Places address autocomplete search to a form. I see the example code HERE. I am using jquery and have my ready function in a separate js file. I have put the example functions into that external js file and it is being loaded.
I have my API key in the Google API script tag. but the callback=initAutocomplete js function is not being called.
My script section looks like -- yes, I have a real API key:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"
integrity="..." crossorigin="anonymous"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=<MY-API-KEY>&libraries=places&callback=initAutocomplete"
async defer></script>
<script src="js/index.js'"></script>
The index.js file looks mostly like:
$(function () {
...
$("#addressLookup").on('focus', geolocate());
});
var autocomplete;
function initAutocomplete() {
// Create the autocomplete object, restricting the search to geographical
// location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {!HTMLInputElement} */(document.getElementById('addressLookup')),
{types: ['geocode']});
// When the user selects an address from the dropdown, populate the address
// fields in the form.
autocomplete.addListener('place_changed', fillInAddress);
}
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
console.log("fillInAddress: place");
console.dir(place);
}
// 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 = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
I don't see anything barfing in the js console log. I do not see the Google stuff loading in the Developer Tools "Network" panel.
What have I missed?

I think you should change scripts order
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"
integrity="..." crossorigin="anonymous"></script>
<script src="js/index.js'"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=<MY-API-KEY>&libraries=places&callback=initAutocomplete"
async defer></script>

Related

Google Places API does not include postal code in autocomplete

I am hoping to get a response, I am trying to auto-populate a user's full address when the first few lines are typed, with ZIP/POSTAL code. The auto suggest populates the entire address minus the zip/postal code. This is needed for all countries.
function initAutocomplete() {
var input = document.getElementById('autocomplete');
var options = {
types: ['address']
};
new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window, 'load', initAutocomplete);

GoogleMap Custom AutoComplete 1 Country

Good afternoon! I found a good code on the web, GoogleMap Custom AutoComplete, you can see it here:
https://embed.plnkr.co/IWj3w4/
In the js script, there are several lines like this:
function initialize() {
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();
});
autocomplete_postalcode = new google.maps.places.Autocomplete(
(document.getElementById("AutocompletePostalCode")), {
types: ['(regions)'],
componentRestrictions: {country: 'fr'}
});
As you can see from the code, it should only work for the "FR" country, but it works worldwide. How to make 1 specific country in this code? For example USA or Canada?
Thanks a lot! I hope for your help

rails 5 turbolinks 5 and google maps how to?

I'm using rails 5 with turbolinks 5 and trying to get google places autocomplete address form to work using the example from google's website found here
I only want to load the javascript and google maps library on this page.
What would be the correct way to get the following javascript to work with rails 5 and turbolinks 5.
<script>
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
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 initAutocomplete() {
// 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.
autocomplete.addListener('place_changed', fillInAddress);
}
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;
}
}
}
// 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 = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete"
async defer></script>
I solved Turbolinks 5 and Google Maps API problem just with data-turbolinks-eval="false" attribute on my google maps script tag.
... application.html.erb
<head>
<!-- Other HTML page Head content -->
<title><%= content_for?(:title) ? yield(:title) : "Untitled" %></title>
<script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY" data-turbolinks-eval="false"></script>
<%= javascript_include_tag "application", 'data-turbolinks-track' => 'reload' %>
</head>
and in your coffee/js files use:
coffee:
$(document).on "turbolinks:load", ->
map = new google.maps.Map $('map').get(0), mapOptions
js:
$(document).on("turbolinks:load", function(){
map = new google.maps.Map($('map').get(0), mapOptions)
})
Try this too....
google.maps.event.addDomListener(window, 'turbolinks:load', initialize);
I was not happy with other answers as Google Maps throws a warning if loaded multiple times, e.g. while re-visiting a page, and disabling Turbolinks defeats its purpose. Also using Google Maps JavaScript API's callback argument forces you to pollute window name space.
Instead we can get Google Maps scripts, e.g. with jQuery, if and only if it is not loaded yet. Here is the CoffeeScript that I use with Rails 4.2.10:
initMap = ->
...
$(document).on 'turbolinks:load', ->
// if you would like to limit what views are affected
// see https://brandonhilkert.com/blog/organizing-javascript-in-rails-application-with-turbolinks/
// return unless $('.plots.map').length > 0
if typeof(google)=='undefined' or typeof(google.maps)=='undefined'
$.get
url: "https://maps.googleapis.com/maps/api/js?key=<use_your_key>&libraries=geometry"
dataType: 'script'
success: initMap
else
initMap()
As per the documentation:
Turbolinks evaluates script elements in a page’s body each time it renders the page. You can use inline body scripts to set up per-page JavaScript state or bootstrap client-side models. To install behavior, or to perform more complex operations when the page changes, avoid script elements and use the turbolinks:load event instead.
But the reason it wasn't working for me was because in layouts/application.html.erb I had:
<%= javascript_include_tag "application", 'data-turbolinks-track' => true %>
when it should be:
<%= javascript_include_tag "application", 'data-turbolinks-track': 'reload' %>

google is not defined, adding autocomplete to google maps

I have the following error, when trying to add the autocomplete function to my google map: google is not defined. I am using the Meteor package dburles:google-maps for the implementation.
Here is my code
.html
<template name="search">
{{> map}}
<div class="container">
<div class="search">
<form>
<label for="location">Location</label>
<input id="search" type="text">
</form>
</div>
</div>
</template>
.js
// Loading map on startup
Meteor.startup(function() {
GoogleMaps.load({ key: 'API-KEY', libraries: 'places' });
var autoComplete = new google.maps.places.Autocomplete(
document.getElementById(search), {
types: ['(cities)']
});
google.maps.event.addListener(autoComplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (place.geometry) {
map.panTo(place.geometry.location);
map.setZoom(15);
}
});
});
Template.map.helpers({
locationsOptions: function() {
// Make sure the maps API has loaded
if (GoogleMaps.loaded()) {
// Map initialization options
return {
center: new google.maps.LatLng(52.524268, 13.406290),
zoom: 12
};
}
}
});
Template.map.onCreated(function() {
// We can use the `ready` callback to interact with the map API once the map is ready.
GoogleMaps.ready('locations', function(map) {
// Add a marker to the map once it's ready
var marker = new google.maps.Marker({
position: map.options.center,
map: map.instance
});
});
});
Any ideas where the error might be coming from?

Google Map generated from typescript / javascript showing as grey box

I've got the following typescript class that produces a google map instance. I'm new to javascript / typescript and HTML!
/// <reference path="./google.maps.d.ts" />
module Mapping {
export class GoogleMap implements IMap {
public name: string;
private map: any;
private options: any;
constructor (mapDiv: Element) {
this.name = "GoogleMap";
this.options = {center: new google.maps.LatLng(53.83305, -1.66412), zoom: 3, MapTypeId: 'terrian' };
this.map = new google.maps.Map(mapDiv, this.options);
}
}
}
and in my view, I have the following ;
<!DOCTYPE html>
<html>
<head><title>TypeScript Mapping</title></head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MyKEYGOESHERE&sensor=false"></script>
<script type="text/javascript" src="~/scripts/require.js"></script>
<script type="text/javascript" src="~/typings/Mapping.js"></script>
<script type="text/javascript">
function initialize() {
var mapCanvas = document.getElementById("map");
Mapping.GoogleMap(mapCanvas);
}
</script>
<body onload="initialize()">
<div id="map" style="height: 512px; width: 512px;"></div>
</body>
</html>
All I get at runtime is a grey box, dragging inside this box changes the pointer to the hand pointer so it looks like the control has been created ok just not showing any maps details.
Anybody got any ideas?
Thanks in advance.
Just to echo the finding from the comments:
It looks like your map options are defined incorrectly. Try...
constructor (mapDiv: Element) {
this.name = "GoogleMap";
this.options = {
center: new google.maps.LatLng(53.83305, -1.66412),
zoom: 3,
MapTypeId: google.maps.MapTypeId.TERRAIN
};
this.map = new google.maps.Map(mapDiv, this.options);
}
Answer:
Google's MapTypeId is an constant so you can directly go for the property here like:
google.maps.MapTypeId.CONSTANT
Currently they support 4 Types:
Constant - Description
HYBRID - Displays a photographic map + roads and city names
ROADMAP - Displays a normal, default 2D map
SATELLITE - Displays a photographic map
TERRAIN - Displays a map with mountains, rivers, etc.
Addon:
I've created a short Demo Application in TypeScript for a Google Maps in an TypeScript Application/Page:
https://github.com/DominikAngerer/typescript-google-maps
It currently support:
Default Google Maps
SnazzyMap Support (simply replace your SnazzyMap with the one I configured in the SnazzyMaps.ts)
Default Center Object
Free Geo IP Location (10.000 Request per Hour)
New Default Icon /images/icon.png
New Default Icon as .PSD /images/icon.psd
No jQuery Needed
Generated Test Data from Json-Generator.com
InfoBox JS Plugin
Infobox Example
Template example for InfoBoxes
Full bower support
On the todo is also typings support, so issue's as you got there shouldn't happen again.

Categories

Resources