How to set center of google map based on street address - javascript

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

Related

Google maps API - add marker by address javascript

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.

Javascript var between files

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

click for show google map

i have one page for show job pic and location . i want when page load first show job pic
and when click on map load instead of pic .
this is may code
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 15,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
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);
}
});
}
google.maps.event.addDomListener(window, 'onclick', initialize);
</script>
<div id="panel">
<input id="address" type="textbox" value="england london">
<input type="button" value="Geocode" onclick="codeAddress();">
</div>
<div id="map-canvas"> <img src="img/src.jpg" /></div>
but when page load first map load and pic not show .
how i can use "button" to swich between image and map and first load image ?
You're initializing the geocoder variable within the initialize() method. So you've call this method before the below method geocoder.geocode(...) like
function codeAddress() {
initialize(); //intialize geocoder
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
....
....
FYI:
Also map-canvas element needs height and width. So set styles like
#map-canvas {
height: 100px;
width: 100px:
}
Check this in JSFiddle
Note:
or either call the initialize() at page load for better performance else each time the Google maps will be initialized.
google.maps.event.addDomListener(window, 'load', initialize);

Only the first marker showing on google map

I have a problem showing addresses on Google Maps. I have tried everything but its not working. It shows only the first marker even if I click on other addresses. How can I get it to show the other markers?
<xsl:for-each select="Attractions/Museums">
<xsl:value-of select="address"/>
</xsl:for-each>
<script type="text/javascript">
var map;
var geocoder = new google.maps.Geocoder();
$( "#maps" ).on( 'pageshow', function() {
google.maps.event.trigger(map,'resize');
})
// initialize the map
function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
function addMarker() {
var address = document.getElementById("addMarker").text;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var image = 'flag1.png';
var markers = new google.maps.Marker({
map: map,
icon: image,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
All your links (anchor tags) have the same ID attribute, so when the function runs it pick the last one to take the marker data from.
Try using different ID attribute for each link and sending the function that ID as a parameter.

javascript google maps geocoder 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.

Categories

Resources