Google Maps Autocomplete not loading in Rails app - javascript

Trying to get Google Maps autocomplete for addresses working. This is the snippet of code I'm using:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&key=<%=ENV['GOOGLE_API_KEY'] %>&libraries=places"></script>
<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>
I've put this inside one of my views and while everything appears to load fine (no console errors), when I type in an address, the dropdown list never appears.
That dropdown box is in a .pac-container div, which does appear, though display:none; when I override that in Chrome dev tools, I just see the google logo appear below my search box (as if the list is empty).
I copied this code to a blank html page outside of my rails app and it worked fine.

It works just fine for me.
I tested this:
<style> #map {height: 90%} </style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<label for="locationTextField">Location</label>
<input id="locationTextField" type="text" size="50">
<div id="map"></div>
<script>
function init() {
var input = document.getElementById('locationTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 50.869754630095834, lng: 4.353812903165801},
zoom: 12
});
}
google.maps.event.addDomListener(window, 'load', init);
</script>
Is there anything you are doing different? Anything I'm missing?

Related

Trying to display latitude and longitude from Google API in JS to HTML

Want to output the latitude and longitude of the marker point in the 2 input boxes below and then also save them but that can happen later. As the user drags around the marker, the latitude and longitude should keep updating. This is the code I have already:
Output
JS
HTML
Please help, I've tried to debug by adding the console.log but it isn't outputting anything which may suggest where the problem is. At least I can't see anything in Chrome dev tools. When I try to debug using Visual Studio breakpoints, none of it loads so I can't do it that way. I've tried a bunch of other stuff as well.
This is the javascript:
var map;
var marker = false;
function initMap() {
var centerOfMap = new google.maps.LatLng(51.487987, -0.237269); // St Paul's School
var options = {
center: centerOfMap,
zoom: 10
};
// extantiate a map object
map = new google.maps.Map(document.getElementById('map'), options);
marker = new google.maps.Marker({
position: centerOfMap,
map: map,
title: 'Drag me around',
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function (event) {
markerLocation();
});
markerLocation();}
function markerLocation() {
// give the information back to the HTML
var currentLocation = marker.getPosition();
console.log(currentLocation.lat());
document.getElementById("lat").value = String.valueOf( currentLocation.lat());
document.getElementById("lng").value = String.valueOf( currentLocation.lng());
}
google.maps.event.addDomListener(window, 'load', initMap);
This is the HTML:
<div class="insert-location">
<p>Select a location where the task will be carried out. Click on a location to select it. Drag the marker to change it.</p>
<div id="map"></div>
<input type="text" id="lat" readonly="readonly"><br>
<input type="text" id="lng" readonly="readonly">
</div>
Ok, here is a working example of how I solved it (add you api key):
http://jsbin.com/rinayek/1/edit?html,css,js,output
1st replace this:
document.getElementById("lat").value = String.valueOf( currentLocation.lat());
document.getElementById("lng").value = String.valueOf( currentLocation.lng());
for this:
document.getElementById("lat").value = currentLocation.lat();
document.getElementById("lng").value = currentLocation.lng();
2nd make your <div id="map"> that is not children of <div class="insert-location">
For the rest you are ok, check the example for more clarity

Google map does not load when displayed onclick

My google map is hidden and it is displayed using ng-show when I click on a previous button. The problem is that it does not load / initialize. It just stays grayed out. I've tried "resize" but does nothing. I've tried using onclick="displayMap()" and using display none/block but it's not working either. No console errors.
This is a known issue (see for example here), the map size is not properly determined once the parent div display style is set to none. Both ng-hide/ng-show directives hides/shows the given element by manipulating display style.
One solution would be to replace ng-show with ng-class/ng-style directives to control the map visibility as demonstrated below:
angular.module('myApp', [])
.controller('MapCtrl', [
'$scope', function ($scope) {
$scope.mapIsVisible = false;
$scope.toggleMap = function(){
$scope.mapIsVisible = !$scope.mapIsVisible;
};
$scope.initMap = function () {
var center = new google.maps.LatLng(-33.870501, 151.206704);
var mapOptions = {
zoom: 12,
center: center,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
$scope.map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
google.maps.event.addDomListener(window, 'load', $scope.initMap);
}]);
#map-canvas {
width: 500px;
height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="https://maps.google.com/maps/api/js"></script>
<script src="script.js"></script>
<div ng-app="myApp">
<div ng-controller="MapCtrl">
<button ng-click="toggleMap()">Toggle map</button>
<div ng-style="{'visibility': mapIsVisible ? 'visible':'hidden'}">
<div id="map-canvas"></div>
</div>
</div>
</div>
You can use callback for this..
function displayMap(){
jQuery("#mapDiv").fadeIn("fast",function(){
initMap();
});
}

Can't get js function to load in html

I've just started trying to develop a website and I'd like to keep the html and javascript separate if I can. I'm trying to put a marker on a map, have the co-ordinates placed in a text box as part of a form, and have them sent to the database when the user submits the form. The code works when it's all inside the html doc, but when I try to separate it it doesnt work. Well, the map still shows up and I can set a marker on it, but it doesn't capture the co-ordinates.
In the head of the html
<script type="text/javascript" src="mapSubmitSighting.js"></script>
<body onload="initMap()">
Inside the div where I want the js to execute
<div id="map">
<div class="map" onclick="initMap();">
<script defer
src="https://maps.googleapis.com/maps/api/js?key==initMap"></script>
</div>
The js file
!function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: 54.621277, lng: -6.692649 }
});
google.maps.event.trigger(map, "resize");
map.addListener('click', function(e) {
placeMarkerAndPanTo(e.latLng, map);
});
}
!function placeMarkerAndPanTo(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
map.panTo(latLng);
document.getElementById("lat").value = latLng.lat();
document.getElementById("lng").value = latLng.lng();
}
I know there's lots wrong with this but if I could just work out how to get the javascript to work it'd be a start. Thank you!
Most part of your code actually works.
Did a few modification though.
Added initial marker position as I noticed that you intended to do this on your sample code.
Also, refactored your code so needed routines will be re-usable.
Please check below.
HTML
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 50%;
}
</style>
<script src="mapSubmitSighting.js"></script>
</head>
<body>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD72DV80rL8PBw2BTTWOwHV3NPSQdx24D8&callback=initMap"></script>
<br/>
<div>
Latitude: <input type="text" id="lat"/><br/><br/>
Longitude: <input type="text" id="lng"/>
</div>
</body>
</html>
JS
function initMap() {
var initialLocation = {lat: 54.621277, lng: -6.692649 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: initialLocation
});
var marker = setMarker(initialLocation, map);
setTextCoordinates(initialLocation.lat, initialLocation.lng);
google.maps.event.trigger(map, "resize");
map.addListener('click', function(e) {
placeMarkerAndPanTo(e.latLng, map);
});
}
function placeMarkerAndPanTo(latLng, map) {
var marker = setMarker(latLng, map);
map.panTo(latLng);
setTextCoordinates(latLng.lat(), latLng.lng());
}
function setMarker(latLng, map){
var marker = new google.maps.Marker({
position: latLng,
map: map
});
return marker;
}
function setTextCoordinates(lat, lng){
document.getElementById("lat").value = lat;
document.getElementById("lng").value = lng;
}
Output
Hope this helps!
You are probably not linking the file correctly.
You can open the developer tools (F12 in Chrome, or just right-click on some part of the page and select Inspect Element) and look at the errors in the console.
Most likely there's a 404 error. Look at the URL of the file, does it match the place where it is supposed to be? Are you missing a folder? Did you forget to upload it? Let us know so we can further assist!
You also do not need the ! in the beginning of your js function. This is preventing your html from reading the js file.
should look like -->
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,`enter code here`

Google Maps API v3.22 reverting to old controls

Google yesterday released v3.22 of their maps api which moves a bunch of the standard controls.
According to the Google Blog at http://googlegeodevelopers.blogspot.co.uk/2015/09/new-controls-style-for-google-maps.html#gpluscomments you can temporarily revert to the old controls, but I can;t get this to work at all.
The blog post says to simply add google.maps.controlsStyle = 'azteca' before you initialize the map, but I'm still getting the old controls displayed and they clash with some of my custom controls.
I've tried adding the line right at the start of my initialize() routine (which sets up all of the map options and creates the map object; and also right before the map = new google.maps.Map() statement.
Has anyone got any pointers as to what I'm doing wrong?
They have a typo in the post (and in the documentation)
Issue in the issue tracker
google.maps.controlsStyle = 'azteca';
should be:
google.maps.controlStyle = 'azteca';
code snippet:
var map;
function initMap() {
google.maps.controlStyle = 'azteca'
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8
});
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#map {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
try this:
google.maps.controlStyle = 'azteca';

show map Google Maps JavaScript API v3

Hi everyone I try to use geolocalization for my webside made with joomla
I obtained the latitude and longitude and fine... But dont show me any map
In my code I am drawing the map inside a div
this is my code
<script type="text/javascript">
function init() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var myLatlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var mapOptions= {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var marcador = new google.maps.Marker();
marcador.setPosition(pos);
marcador.setMap(map);
}, function() {
alert("su navegador no acepta geolocalización");
});
}
}
google.maps.event.addDomListener(window, 'load', init);
</script>
in my head I have this
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js?ver=3.1.2'></script>
and his in my body
<div id="map"></div>
I have been read other post with the same problem, but I don't find the error in my code.
Thanks
There are some small errors in your code - hint: try using the Javascript console in Chrome to see these errors:
You do not have 'pos' defined here: marcador.setPosition(pos);
...and you want to create a marker with it, so you have to use the LatLng object
give your div a width and height (if you have not done it in your CSS file)
Here is a JSFiddle with all there errors fixed
Where is pos defined? This will most likely cause a JS error which will prevent the map displaying.
marcador.setPosition(pos);
Give your div a size(width and height):
<div id="map" style="width:400px;height:300px"></div>
You need to set width and height values for your #map and make sure the init() is called
here my jsfiddle : http://jsfiddle.net/3MTtc/1/

Categories

Resources