Google maps API - add marker by address javascript - 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.

Related

Google maps not displayed in website

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

Multiple Google Maps icons?

I'm trying to combine the following two blocks of codes together.
but for some reason, when i load the page in the browser, First the second blocks of code loads the marker on the map and then the page refreshes and the first blocks of code loads on the map!
This is my entire code:
<!DOCTYPE html>
<html>
<head>
<title>Google maps</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
geocoder = new google.maps.Geocoder();
function initialize() {
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
codeAddress();
}
function codeAddress() {
var address = '<?= $_GET['location'] ?>';
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({
icon: 'meicon.png',
map: map,
position: results[0].geometry.location
});
} else {
alert("Error loading map");
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<script type="text/javascript">
var locations = [
['Bondi Beach', 51.5033631,-0.1276253, 1]
];
var maps = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 15,
center: new google.maps.LatLng(51.5033630,-0.1276250),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var markers, i;
for (i = 0; i < locations.length; i++) {
markers = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: maps
});
google.maps.event.addListener(markers, 'click', (function(markers, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, markers);
}
})(markers, i));
}
</script>
</body>
</html>
could someone please advise on this issue?
Thanks in advance.
It's probably because you're calling the geocoder on the address in the first block, which is an async call to google to check the address. While the code is talking to google the page runs the second code block. When that call returns it runs the rest of the code in the first block, which sets the center of the map.
The reason is simple you are loading two map the first called in <head> script what build a map in map-canvas named map. the second in body script you create another map named maps and this too create in map-canvas.You need only a working map and with this do what you nedd.

Reverse Geocoding in Oracle Apex (From draggable marker)

I currently enabled user to put the address into text-boxes and display the address on Google map, but I want to do the opposite now and get nearest matching address to the text-boxes (which are on a separate region, same page) from a draggable marker. I heard that I should use JSON with PHP or PL/JSON to get the data from the map to the text-boxes. However, I do not have any knowledge about JSON and I think Google map API provide this sort of geocoding methods inside the JavaScript. I am not sure how to fully apply it, and if it is possible to get both methods in one page (or maybe I should use some procedure with JavaScript and call it on the page, not sure). Here is my code so far in the HTML Header of the page:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
var uniLatLng = new google.maps.LatLng (51.887496, -2.088788);
var geocoder = new google.maps.Geocoder();
var map;
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
},
function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
}
else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('P15_ADDRESS').value;
}
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 16,
center: uniLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
};
var marker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
flat: false,
position: new google.maps.LatLng(59.327383, 18.06747)
})
function map_canvas() {
var address = "&P15_ADDRESS.";
geocoder.geocode( { 'address': address, 'region': "GB"}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
flat: false,
position: results[0].geometry.location
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
Page HTML Body Attribute - onload="initialize(), map_canvas()"
Any suggestions how can I achieve this?
I think this example does what you want on the Reverse Geocoding part. https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
the only thing you need to add to this is a draggable marker with a listener for on dragged, which would update the position and call the same methods as it is in the Reverse Geocode button.

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