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
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 am trying to integrate Google Maps into a WebBrowserControl in my C# WPF program. The map loads in the control and centers on the correct latitude and longitude, however I am having a couple of errors. First of all, the map loads and after a couple of seconds I get an error box appear;
Secondly, when I am trying to add a marker on the location of the latitude and longitude, I get an error even before the map loads at all. Here is my code so far;
mapWebBrowser.NavigateToString(#"<html xmlns=""http://www.w3.org/1999/xhtml"" xmlns:v=""urn:schemas-microsoft-com:vml"">
<head>
<meta http - equiv = ""X-UA-Compatible"" content = ""IE=edge""/>
<meta name = ""viewport"" content = ""initial-scale=1.0, user-scalable=no""/>
<script type = ""text/javascript""
src = ""http://maps.google.com.mx/maps/api/js?sensor=true&language=""es"" ></script>
<script src = 'http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js'>
</script><script type = ""text/javascript"">
function initialize() {
var latlng = new google.maps.LatLng(" + latitude + ", " + longitude + #");
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(""map_canvas""), myOptions);
}
function addMarker( Lat, Long) {
var latLng = new google.maps.LatLng(Lat, Long);
marker = new google.maps.Marker({
position: latLng,
draggable: false,
animation: google.maps.Animation.DROP,
});
markers.push(marker);
var markerCluster = new MarkerClusterer(map, markers)
}
</script>
</head>
<body onload = ""initialize()"" >
<div id=""map_canvas"" style=""width:100%; height:100%""></div>
</body>
</html>");
This is the function I am attempting to use to add a marker onto the map;
function addMarker( Lat, Long) {
var latLng = new google.maps.LatLng(Lat, Long);
marker = new google.maps.Marker({
position: latLng,
draggable: false,
animation: google.maps.Animation.DROP,
});
markers.push(marker);
var markerCluster = new MarkerClusterer(map, markers)
}
Which I call in C#;
mapWebBrowser.InvokeScript("addMarker", new object[] { latitude, longitude } );
Unfortunately as I stated before both methods are causing issues.
I believe there was a change in Google's APIs back in June and they now require authentication for google maps. I don't see your API key being supplied anywhere. I would suggest you try your HTML/javascript in the browser or where you can sniff the requests and the responses and see what's going on.
If you still can't solve your problem. You may use Script Errors Suppressed too. Then this window will disappear.
webBrowser1.ScriptErrorsSuppressed = true;
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.
i am trying to implement google map in chrome, however the geolocation doesn't seems to be working i also changed the setting to 'allow all site to track'
i have taken these code from a tutorial online, and hence i couldn't find a way to make it work
<head>
<title>Map</title>
<!-- Google Maps and Places API -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function initGeolocation(){
if( navigator.geolocation ){
// Call getCurrentPosition with success and failure callbacks
navigator.geolocation.getCurrentPosition( success, fail );
}else{
alert("Sorry, your browser does not support geolocation services.");
}
}
var map;
function success(position){
// Define the coordinates as a Google Maps LatLng Object
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Prepare the map options
var mapOptions = {
zoom: 14,
center: coords,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Create the map, and place it in the map_canvas div
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//search for schools within 1500 metres of our current location, and as a marker use school.png
//placesRequest('Schools',coords,1500,['school']);
// Place the initial marker
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "Your current location!"
});
}
function fail(){
// Could not obtain location
}
//Request places from Google
function placesRequest(title,latlng,radius,types,icon){
//Parameters for our places request
var request = {
location: latlng,
radius: radius,
types: types
};
//Make the service call to google
var callPlaces = new google.maps.places.PlacesService(map);
callPlaces.search(request, function(results,status){
//trace what Google gives us back
$.each(results, function(i,place){
var placeLoc = place.geometry.location;
var thisplace = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon,
title: place.name
});
})
});
}
</script>
initGeolocation() is not fired anywhere.
The div with id map_canvas is missing and you don't call initGeolocation function anywhere in your code .
Check here , everything works ok
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.