Google maps api v3, defining user current location - javascript

function onPositionUpdate(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var markerPoint = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
position: markerPoint,
map: map,
title: 'Your Location'
});
}
function button_clicked() {
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition(onPositionUpdate);
else
alert("navigator.geolocation is not available");
}
This code is running correctly and shows user location. when I try this at home this shows correct address but when I try this at another location this code doesn't show correct address. why? I dont know how this code run exactly(does this code define for IP or other information)

You can check if another program can find you. If not, it might be that its not your code which is incorrect:
http://html5demos.com/geo
Some security measures might cause that the client won't share location informations automatically.

Have you tried :
navigator.geolocation.getCurrentPosition(onPositionUpdate() );
Not sure if your callback has to have brackets or not. It's something I would try.
I also noticed that geolocation takes a little while to narrow down the approximation to a smaller radius. Might have to call position update.

Related

Sorry, we have no imagery here - Google Satellite Map

I am using Google Satellite map on an application. It was working fine and suddenly the map images start not showing. Instead of the terrain images, the map is showing the message "Sorry, we have no imagery here".
It is happening on my office IP and other testers' IPs. If I access from another IP or mobile data it works and shown the satellite images. I am not sure if google blocks IPs in case of continuous access on the maps.
Also I am able to see a lot of errors accessing the images
While clicking on the links for loading images, I am getting an error page like below instead of the map tile image.
Any clues on this issue is appreciated
To avoid showing these errors, in case they are due to the use of a zoom level that is too high for the area you are viewing, you can use the MaxZoomService. Kindly note that the below code snippet doesn't work because apparently access to the service without an API key is not possible.
Copy the code and test it with a working API key.
var map, maxZoomService;
function initialize() {
maxZoomService = new google.maps.MaxZoomService();
var myLatLng = new google.maps.LatLng(0, 0);
var mapOptions = {
zoom: 15,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatLng,
map: map
});
google.maps.event.addListenerOnce(map, 'idle', function() {
checkZoom();
});
google.maps.event.addListener(map, 'zoom_changed', function() {
checkZoom();
});
}
function checkZoom() {
let zoom = map.getZoom();
maxZoomService.getMaxZoomAtLatLng(map.getCenter(), function(response) {
if (response.status !== 'OK') {
alert('maxZoomService error: ' + response.status);
document.getElementById('max-zoom').innerHTML = 'n/a';
document.getElementById('max-zoom-service').innerHTML = response.status;
} else {
if (response.zoom < zoom) {
map.setZoom(response.zoom);
document.getElementById('max-zoom').innerHTML = response.zoom;
document.getElementById('max-zoom-service').innerHTML = response.status;
}
}
document.getElementById('curr-zoom').innerHTML = map.getZoom();
});
}
initialize();
#map-canvas {
height: 130px;
}
span {
font-weight: bold;
}
<div id="map-canvas"></div>
Current Zoom Level: <span id="curr-zoom"></span><br>
Max Zoom Level: <span id="max-zoom"></span><br>
Max Zoom Service Status: <span id="max-zoom-service"></span>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
If the zoom level is not the issue, make sure that you are using a valid API key. In any case, it might be worth creating a new key and trying again with that one. If that still doesn't work, I would try to contact Google directly with more information as it might be that your network IP or IP range was banned by Google for some reason.
I know this is an old question but, I recently got this error too. So, the problem, in my case was the version of the API script I was using.
I'm answering this because I didn't found this solution over here, so, just in case someone was getting the same error.
Just adding v=3.35 (version number) to the url and it works.
Example: https://maps.googleapis.com/maps/api/js?v=3.35&key=API_KEY...
They explain here:
https://developers.google.com/maps/documentation/javascript/versions#an-update-affected-my-application
Thank you for all the response and I was able to find and fix the real issue. Adding the details here for reference.
I have contacted Google support with the request details and they were able to figure out the exact problem. The reason is their image servers are blocking the request from this project (hybrid mobile project - Android) since it found out that there are invalid request is also coming from the project. The invalid request is referred to as the requests without proper header information.
Based on that information, I could find out that a caching mechanism in the project was trying to cache the images and that is which sends the invalid requests. Adding proper header to that cache mechanism solved the issue forever.

Geolocation doesn't work with cordova

I'm currently working on a mobile application with Intel XDK (In background it's Cordova finally, that's why I put Cordova in title.)
With an Ajax request, I get some adresses and with these adresses I want to calculate the distance between them and the current position of user.
So, I get adresses, I convert them and I make the difference.
But actually, nothing is working !
function codeAddress(id, addresse) {
geocoder.geocode( { 'address': addresse}, function(results, status) {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function(){}, 100);
}
console.log(id);
console.log(addresse);
//document.addEventListener("intel.xdk.device.ready",function(){
if (navigator.geolocation)
{
if (status == google.maps.GeocoderStatus.OK)
{
navigator.geolocation.getCurrentPosition(function(position) {
addressEvent = results[0].geometry.location;
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var position = new google.maps.LatLng(pos.lat, pos.lng)
var resultat = google.maps.geometry.spherical.computeDistanceBetween(addressEvent, position);
console.log(resultat);
console.log(addressEvent);
console.log(pos);
console.log(position);
var convert = Math.floor(resultat);
var finalConvert = convert + " m";
var distance = document.createElement('span');
distance.innerHTML = finalConvert;
distance.className = "geo";
document.getElementsByClassName('meta-info-geo')[id].appendChild(distance);
}, function() {
handleLocationError(true, infoWindow);
});
}
}
//},false);
});
}
In the console.log(id), console.log(addresse), I HAVE results !
Actually i'm getting 4 IDs and 4 adresses.
I checked on all the topics I could find on StackOverFlow, and I had normally to add the line in // with the addEventListener but it changes nothing.
Is there someone who knows how to change that ?
ps : Of course, cordova geoloc is in the build and permissions are granted !
EDIT : I'm targeting Android 4.0 min and iOS 5.1.1. I'm using SDK.
EDIT 2 :
Geolocation frequently does not work the way people expect it to work, for a variety of reasons that have been expressed here and here.
You can experiment with geo by using the "Hello, Cordova" sample app that is in the XDK and also available on GitHub. Try using it on a variety of devices to see how things work. Push the "fine" button to initiate a single geo call for a "fine" location and push the "coarse" button to initiate a single geo call for a "coarse" location. Push the "watch" button to initiate a request for a series of geo data points (set to coarse or fine by pushing one of the single buttons first).
The behavior you get in the Emulate tab will be dramatically different than what you get on a real device. The type of device (Android, iOS, etc.) and the version of that device will influence your results; the manufacturer of the device and your location (inside or outside) will influence your results. Do not assume that making a call to the geo APIs will always give you immediate and reliable data, geolocation hardware does not work that way... In fact, you cannot assume that you can even get a valid result! See the two links I pointed to earlier in the post for some reasons why.

HTML 5 Issues with showing google map

I have been looking at the google maps html5/javascript code and am attempting to make a app which finds someone current location through longitude and latitude then geo reverses it to give then their address. However when i run the code it just gives a blank screen. I am really new to html5 and if anyone could point to me what i am doing wrong i would be really grateful.
the error is geocoder = new google.maps.Geocoder(): must be geocoder = new google.maps.Geocoder();
By default, navigator.geolocation.getCurrentPosition() has a timeout value of infinite. In the getCurrentPosition's options parameter, specify a timeout value and I think you will find that is where your error lies.
... }, function() {
handleNoGeolocation(true);
}, { timeout: 4000 });

Detect Google Static StreetView API Imagery availability

I know there are at least a couple of questions like this
detecting "we have no imagery" of google maps street view static images
How can I tell if Google's Streetview Image API Returns "Sorry, we have no imagery here" (ie. NULL) Result?
These articles offer a couple of solutions. The two most popular I've seen here and via Google searaches are:
Detecting the size of the image to determine if you got a "good" image or not from the google static image API
Call the getPanoramaByLocation service to determine if streetview is available for a location
Unfortunately, I don't want to use the first solution because it feels like the hack, and the second solution does not always seem to work.
var center = new google.maps.LatLng(latitude, longitude);
var streetViewService = new google.maps.StreetViewService();
var maxDistanceFromCenter = 75; //meters
streetViewService.getPanoramaByLocation(center, maxDistanceFromCenter, function (streetViewPanoramaData, status) {
if (status === google.maps.StreetViewStatus.OK) {
var key = /**smarty** #mapKey# **smarty**/;
var url = 'http://maps.googleapis.com/maps/api/streetview?size=320x320&location=' + latitude + ',%20' + longitude + '&sensor=false&key=' + key;
jQuery('.ui-page-active .streetView').attr('src', url);
} else {
console.log('error calling street view');
}
});
};
This code will correctly determine if panoramic imagery is available for a location, BUT sometimes static imagery is not available for that exact same location.
I started at 100 for my getPanoramaByLocation radius and that seemed like a safe number, but then I found a case where I was getting the "Sorry, we have no imagery here" error. So I went to 75, now I have to go to 50.
It seems like getPanoramaByLocation is not a safe indicator of static streetview imagery being available, or maybe it is but there's a particular value for the radius that should be used. I can't find it in the docs though. So my question: what's the safest radius to use for my maxDistanceFromCenter?

problem with google directions api

A user comes to my web app and locates the destination address but he does not locate the source location and publishes the page. The normal user who are not registered to the web app adds the source location.
Once the user adds the source location he is not able to see the exact direction map, rather the google is displaying the default maps.
Here is the exception giving when we used chrome console.
I have added the code here and also the exception I am getting
Error Name:
main.js:41Uncaught TypeError:Object#<object> has no method 'Load'
function calcRoute() {
showDirections();
document.getElementById('directionsPanel').innerHTML="";
initialize();
var start = document.getElementById("txt_from").value;
var end = getDestinationAdderss(document.getElementById('final_address').innerHTML);
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas_directions"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}
You have removed some code that is present in the Google sample.
directionsDisplay = new google.maps.DirectionsRenderer({
'map': map,
'preserveViewport': true,
'draggable': true
});
I expect that your code is working again if you add the code above in the proper place. If not, you really should start with the sample code again, since that does work.
The debug screenshot indicates that initialize() is the last bit of code run in your file before Google Maps API throws the error. So look in there (and/or provide that code in your question).
UPDATE: Based on your code, the first to check might be to make sure that there is an element with an id of map_canvas_directions and another one with an id of directionsPanel. There's not enough information to say for sure, but if I had to guess, your UI changes got rid of one or the other of those elements, but your code requires them.
UPDATE TO THE UPDATE: Replacing the stuff in the DirectionsRenderer() constructor as #Arjan suggests is also a likely cause of your problem so definitely try that too!

Categories