1

Google geolocation with Javascript is not working in live site for major browsers like Firefox, Chrome. Geolocation result is displaying in Opera for live site, where as the same is working in localhost for all browsers (Chrome, firefox & Opera). My Live site protocol using https://. See below code and suggest any.. Geolocation and Google Maps API

<script src="http://maps.google.com/maps/api/js?key=MY_KEY_HERE&sensor=true"></script>

<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script>

function writeAddressName(latLng) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"location": latLng
},
function(results, status) {
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {

//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_2") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
//alert(city.short_name + " " + city.long_name);
//alert(city.long_name);
var cityname = city.long_name;
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById("address").innerHTML = results[0].formatted_address;
document.getElementById("citynm").innerHTML = cityname;  }
else {
document.getElementById("error").innerHTML += "Unable to retrieve your address" + "<br>"; }
});
}
function geolocationSuccess(position) {
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Write the formatted address
writeAddressName(userLatLng);

var myOptions = {
zoom : 16,
center : userLatLng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// Draw the map
var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
// Place the marker
new google.maps.Marker({
map: mapObject,
position: userLatLng
});
// Draw a circle around the user position to have an idea of the current localization accuracy
var circle = new google.maps.Circle({
center: userLatLng,
radius: position.coords.accuracy,
map: mapObject,
fillColor: '#0000FF',
fillOpacity: 0.5,
strokeColor: '#0000FF',
strokeOpacity: 1.0
});
mapObject.fitBounds(circle.getBounds());
}

function geolocationError(positionError) {
document.getElementById("error").innerHTML += "Error: " + positionError.message + "<br>";
}

function geolocateUser() {
// If the browser supports the Geolocation API
if (navigator.geolocation)
{
var positionOptions = {
enableHighAccuracy: true,
timeout: 10 * 1000 // 10 seconds
};
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError, positionOptions);
}
else
document.getElementById("error").innerHTML += "Your browser doesn't support the Geolocation API";
}
window.onload = geolocateUser;
</script>
</head>
<body>
<p id="citynm"></p>
<p id="address"></p>
</body>
</html>
J Sinha
  • 135
  • 3
  • 10

3 Answers3

1

I have tested you codes (Chrome v29, Windows 8), the one below works from a remote server (non-local host) but you need note note 2 areas

<script src="http://maps.google.com/maps/api/js?v=3.9&sensor=true"></script>

I added v=3.9

And

function writeAddressName(latLng) {
    ...
    if (results[0].address_components[i].types[b] == "route") {

You may need to handle case where city cannot be set.

I can see the address. [This sample does not include map display]

<!DOCTYPE html>
<html>
<head>

<script src="http://maps.google.com/maps/api/js?v=3.9&sensor=true"></script>
<script>
function writeAddressName(latLng) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ "location": latLng }, function(results, status) {
        for (var i=0; i<results[0].address_components.length; i++) {
            for (var b=0;b<results[0].address_components[i].types.length;b++) {
                //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
                if (results[0].address_components[i].types[b] == "route") {
                //this is the object you are looking for
                    city = results[0].address_components[i];
                    break;
                }
            }
        }
//alert(city.short_name + " " + city.long_name);
//alert(city.long_name);
        var cityname = city.long_name;
        if (status == google.maps.GeocoderStatus.OK) {
            document.getElementById("address").innerHTML = results[0].formatted_address;
            document.getElementById("citynm").innerHTML = cityname;
        }
        else {
            document.getElementById("error").innerHTML += "Unable to retrieve your address" + "<br>";
        }
    });
}

function geolocationSuccess(position) {
    var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Write the formatted address
    writeAddressName(userLatLng);

    var myOptions = {
        zoom : 16,
        center : userLatLng,
        mapTypeId : google.maps.MapTypeId.ROADMAP
    };
    // Draw the map
    var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);
    // Place the marker
    new google.maps.Marker({
        map: mapObject,
        position: userLatLng
    });
// Draw a circle around the user position to have an idea of the current localization accuracy
    var circle = new google.maps.Circle({
        center: userLatLng,
        radius: position.coords.accuracy,
        map: mapObject,
        fillColor: '#0000FF',
        fillOpacity: 0.5,
        strokeColor: '#0000FF',
        strokeOpacity: 1.0
    });
    mapObject.fitBounds(circle.getBounds());
}

function geolocationError(positionError) {
    document.getElementById("error").innerHTML += "Error: " + positionError.message + "<br>";
}

function geolocateUser() {
    // If the browser supports the Geolocation API
    if (navigator.geolocation) {
        var positionOptions = {
            enableHighAccuracy: true,
            timeout: 10 * 1000 // 10 seconds
        };
        navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError, positionOptions);
    }
    else
    document.getElementById("error").innerHTML += "Your browser doesn't support the Geolocation API";
}
window.onload = geolocateUser;
</script>
</head>
<body>
<p id="error"></p>
<p id="citynm"></p>
<p id="address"></p>
</body>
</html>
Aaron Gong
  • 977
  • 7
  • 18
  • ..Thanks for your effort still I am not getting alert message here in firefox var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); alert(userLatLng); // alert with coordinate points are not dispalying. Anyway as per the requirement, here I am using ajax and redirecting geo points to another page. I have just one last issue... Geo point alerts appearing in chrome and opera.. but not working in firefox. Strangely, few times those alert popups in firefox also appeared, now it is not at all working.. Plz suggest to work in firefox also – J Sinha Sep 05 '13 at 08:44
  • could you try console.log(google, position); before calling the google.maps.LatLng(...) to see if google and position objects is ok? use firebug on firefox to check the console output instead of using alert, you get more info – Aaron Gong Sep 05 '13 at 09:00
  • Yeah.. I checked it in console Error: Blocked loading mixed active content "http://maps.google.com/maps/api/js?key= ... & Blocked loading mixed active content "http://maps.google.com/maps/api/js?v=3.9&sensor=true" – J Sinha Sep 05 '13 at 09:36
  • maybe your page is https and you calling using http. http://stackoverflow.com/questions/18251128/why-am-i-suddenly-getting-a-blocked-loading-mixed-active-content-issue-in-fire – Aaron Gong Sep 05 '13 at 09:42
  • I changed to https:// now above two erros are not coming.. Another error "TypeError: cd is not a function" in main.js (line 47) file. Path showing "https://maps.gstatic.com/intl/en_us/mapfiles/api-3/12/17/main.js" – J Sinha Sep 05 '13 at 10:07
  • I got that error too earlier on, what I did was just comment out all the javascript and slowly put them on 1 by 1, it may (just guess) have something to do with function writeAddressName(latLng) { ... if (results[0].address_components[i].types[b] == "route") {, the hardcoded string – Aaron Gong Sep 05 '13 at 10:19
0

May be this links can help you

https://developers.google.com/maps/articles/geocodestrat

google maps api works at localhost but doesn't work at web server

Community
  • 1
  • 1
sourav
  • 676
  • 5
  • 21
  • @Sourav... your answered 2nd link is useful. I am not getting alert message at this below point var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); alert(userLatLng); // alert with coordinate points are not dispalying. Anyway as per the requirement, here I am using ajax and redirecting geo points to another page. I have just one last issue... Geo point alerts appearing in chrome and opera.. but not working in firefox. Strangely, few times those alert popups in firefox also appeared, now it is not at all working.. Plz suggest to work in firefox also – J Sinha Sep 05 '13 at 08:41
0
https://developers.google.com/maps/faq?hl=en&csw=1#browsersupport



https://developers.google.com/maps/documentation/javascript/examples/map-geolocation

http://jsfiddle.net/BQzLq/3/

https://support.google.com/maps/answer/21849?hl=en

http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

These all links is just for your knowledge in some browser or browser's older versions google map v3 doesn't works.
Anup
  • 3,283
  • 1
  • 28
  • 37
  • ..Thanks for your effort still I am not getting alert message here in firefox var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); alert(userLatLng); // alert with coordinate points are not dispalying. Anyway as per the requirement, here I am using ajax and redirecting geo points to another page. I have just one last issue... Geo point alerts appearing in chrome and opera.. but not working in firefox. Strangely, few times those alert popups in firefox also appeared, now it is not at all working.. Plz suggest to work in firefox also – J Sinha Sep 05 '13 at 08:45