I am having problems importing a variable into a js function run from a callback as:
<script type="text/javascript" src="/javascripts/maps.js"> </script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=<%= mapkey%>
&libraries=visualization&callback=initMap">
</script>
The problem is I cannot use a global variable or external function inside initMap. I am using nodejs.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
var geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function() {
geocodeAddress(geocoder, map);
});
}
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
As the moment the address is taken from the html form or can be explicitly defined:
var address = document.getElementById('address').value; or
var address = ["place", "place"]
However I need to be able to use a global variable or an exported function:
var address = global_locations (defined elsewhere as a global.gobal_locations = ["place", "place"] and works in other files) or
var address = loc.getAddresses();
I dont understand async enough to be able to do this
You could use window and create a namespace for your variables which you want to access globally.
Please check this answer from Blazemonger in Storing a variable in the JavaScript 'window' object is a proper way to use that object?.
This will help you where you want to go, I think.
You can add a dynamic script loading function, like this:
function loadjs(filename){
var jsfile=document.createElement('script')
ref.setAttribute("type","text/javascript")
ref.setAttribute("src", filename)
}
loadjs("myscript.js")
Related
I have database of places with addresses and I want to add markers on google maps.
It shows only the default marker, seems like the geocoder.geocode() does nothing. For an example I'm trying to add a marker on " New York City", with no success.
<script>
var geocoder;
var map;
var address = "new york city";
geocoder = new google.maps.Geocoder();
function initMap() {
var uluru = { lat: -25.363, lng: 131.044 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
codeAddress(address);
}
function codeAddress(address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == 'OK') {
var marker = new google.maps.Marker({
position: address,
map: map
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=XXX&callback=initMap"
async defer></script>
The reason why you are not getting the expected result is because there is incorrect codes placement in the example you provided. You are trying to get a new instance of Google Maps API Geocoder before Google Maps is fully loaded. Hence, Google Maps API Geocoder will not work because of this Uncaught ReferenceError: google is not defined. You should get a new instance of Google Maps API Geocoder inside the initMap() function.
You can check Maps JavaScript API Geocoding
to learn more.
You can also check Best Practices When Geocoding Addresses.
Please also note that you should not include your API_KEY when posting Google Maps APi related questions.
Here's the whole code:
<!DOCTYPE html>
<html>
<head>
<title>Geocoding service</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var geocoder;
var map;
var address = "new york city";
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
geocoder = new google.maps.Geocoder();
codeAddress(geocoder, map);
}
function codeAddress(geocoder, map) {
geocoder.geocode({'address': address}, function(results, status) {
if (status === '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);
}
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
Live demo here.
Hope it helps!
There were several errors in your code. Normally, it should looks OK now:
var geocoder;
var map;
var address = "new york city";
function initMap() {
geocoder = new google.maps.Geocoder();
var uluru = { lat: -25.363, lng: 131.044 };
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
codeAddress(address);
}
function codeAddress(address) {
geocoder.geocode({ 'address': address }, function (results, status) {
console.log(results);
var latLng = {lat: results[0].geometry.location.lat (), lng: results[0].geometry.location.lng ()};
console.log (latLng);
if (status == 'OK') {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
console.log (map);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
This is a list of your errors:
You have to initialize your geocode when the google maps api is fully loaded. It means that you have to put this line of code:geocoder = new google.maps.Geocoder(); in the initMap ().
When you initialize the map you have to refer to a global variable. In your code, you create a new variable map in your function. But, you have to pass by the global's variable map.
When, you want to get the position of the geocoder's result, you have to pass by this line of code:results[0].geometry.location.lat ().
You may refer to the documentation.
Tell me if you have some questions.
I have just started working with the Google Maps API and Geocoding Service. I followed this tutorial and it was great.
Now I want to be able to create a map with a center based on a location ( "Vancvouer, BC" ) as opposed to latitude and longtitude as required when creating the map.
What I am trying to do is use a callback function named "initMap()" to initialize the map, and in that function I am creating a Geocoder object to get lang and long based on a location. ( "Vancvouer, BC" ).
Here's my initMap() function:
function initMap() {
var geocoder1 = new google.maps.Geocoder();
var center = getCenter(geocoder1, 'Vancouver, BC');
if(center != null) {
alert(center[0].geometry.location);
}
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
}
This is how I am getting lang and long based on address:
function getCenter(geocoder, address) {
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
console.log(results);
var result = results[0].geometry.location.toJSON();
return result;
} else {
alert('Geocode was not successful for the following reason: ' + status);
// return null;
}
});
}
This will return a JSON object with the lat and lang I want, but when I try to access its values in initMap() using the if statement center is always undefined.
Once I am able to get the value for center I believe I would be able to set the center easy enough, but why I am not getting these values?
I think its a problem with scope and callback functions, but cant figure it out. Been stuck for a while, thought I'd reach out for help.
Thanks,
Matt
P.S. Let me know if you need any other info. First post on stackoverflow...
The geocoder is asynchronous, you can't return anything from an asynchronous callback function. You need to use the returned data inside the callback function where/when it is available:
function setCenter(geocoder, address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
// return null;
}
});
}
proof of concept fiddle
code snippet:
function initMap() {
var geocoder1 = new google.maps.Geocoder();
setCenter(geocoder1, 'Vancouver, BC');
}
function setCenter(geocoder, address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
// return null;
}
});
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
You do not need to convert the results to Json. Use
center[0].geometry.location
This can be assigned to the center property of the map object. To check for null:
if (center[0] != null)
Set center by address after map ini:
example:
set_center(address)
function set_center(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
}
})
}
var "map" must be ini with google map, example
var map = new google.maps.Map(document.getElementById('main-map'), mapOptions);
I am currently stuck on getting google maps to display on a site. This worked in a dev environment after a while. I came to put this into live and thought that I would just need the API key in the src
What I have is
<script src="https://maps.googleapis.com/maps/api/js?key=MY_API CODE HERE&callback=initMap"
async defer></script>
<script type="text/javascript">
initialize();
function initialize() {
google.maps.event.addDomListener(window, 'load', function () {
codeAddress("#Model.Postcode, #Model.Address");
});
}
var geocoder;
var map;
function codeAddress(address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 17,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
// create a marker
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: 'Latitude: ' + results[0].geometry.location.Ya + ' Longitude :' + results[0].geometry.location.Za
});
}
});
}
But this only produces the error of
This page was unable to display a Google Maps element. The provided Google API key is invalid or this site is not authorized to use it.
Many thanks
You first have to obtain an API key from the website and replace it with the "MY_API CODE HERE" part
That should be working, just because we all make mistakes, are you sure you copied the API key correctly? You need to make sure the trailing '&' is still in there after you add the key.
You could also try generating another key and using that. The process for doing that is here: https://developers.google.com/maps/documentation/javascript/get-api-key#key
I have google maps implemented and I am getting latitude and longitude, I want thse values to be used outside of the google maps function. I can add them to the DOM only when I call these variables within the google maps code. How can I use these variables outside to google maps function.
On click of the maps, I need to append these latitude and longitude values to the URL as a querystring.
I am not sure how Closures work exactly. Can someone please help me adding these latitude and longitude values to the querystring outside of google maps initilaize() function.
Below is my code;
<script>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(44.397, -122.644),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(44.397, -122.644),
map: map,
draggable: true
});
google.maps.event.addListener(map, 'mousemove', function ques(event) {
var lat_value = event.latLng.lat();
var lon_value = event.latLng.lng();
document.getElementById("llat").value = lat_value;
document.getElementById("llon").value = lon_value;
});
google.maps.event.addListener(map, 'click', function cclick() {
})
}
</script>
<script>
$(function () {
// Access functions and variables defined in google maps initialize() function here
if(document.location.href.indexOf('?') == -1) {
window.location = window.location + "?lat_value";
}
});
</script>
FIDDLE
You don't need to use a JS closure here. You don't even need to write the handler outside of the scope of that initialize method. Just do it the same way you did the mousemove handler:
google.maps.event.addListener(map, 'click', function (e) {
var lat_value = e.latLng.lat();
var lon_value = e.latLng.lng();
window.location = window.location.href.split('?')[0]
+ "?lat_value=" + lat_value
+ "&long_value=" + lon_value;
});
In general though, if you wanted to have access to your mapOptions variable outside of initialize, just define it in the outer-scope (i.e. do the var mapOptions declaration before function initialize).
I am trying to use the google maps javascript API to map an address based on this example.
https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-simple
The documentation recommends the clientside javascript approach as the best way to deal with quotas on requests. So far so good. My problem is in moving from this example to my specific case. My addresses are already in a database so I don't need the user to enter one. Also I do not want the map to load with the page. Instead, I want the map for the address to load when the user clicks a link.
I have a script working that loads the map in a div using initialize (). But my problem is getting initialize to work with geocode. The geocode in the example depends on initialize loading with bodyonload which I do not want.
Here is code. Would appreciate any suggestions:
javascript
var map;
var geocoder;
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, 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);
}
});
}
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.7562008,-73.9903784);
var myOptions = {
zoom: 18,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
html
<input id="address" type="hidden" value="Palo Alto CA">
View map without geocoding
<div id="map_canvas" style="width:300px; height:300px;"></div>
View map of geocoded address
The only issue I had with your script was the following line in the initialize() function:
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
By declaring var map, your script is just declaring a local variable named map, as opposed to using the global map variable declared at the top of your script.
By removing var, the script uses the global variable and runs fine:
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
Finally, to get the geocoded map to load on the link click, change onclick for your geocoded address to onclick="initialize();codeAddress();".
Added:
Try combining your initialize() and codeAddress() methods into the following:
function initialize() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById('address').value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 18,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
And then just call initialize() from your link.
Basically, what we're doing is taking the call to geocoder.geocode() that codeAddress() was performing and inside the resulting delegate, we're using results[0].geometry.location to initialize the map. This way, the temporary latlong doesn't need to be displayed.