I would like to get the address string of the current user location. Is that possible?
Many thanks.
Regards
the user's location is available in google.loader.ClientLocation (this will contain a guess based on the client IP if the IP is known)
google.loader.ClientLocation
When an application makes use of the
AJAX API loader, the loader attempts
to geo locate the client based on its
IP address. If this process succeeds,
the client's location, scoped to the
metro level, is made available in the
google.loader.ClientLocation property.
If the process fails to find a match,
this property is set to null.
http://code.google.com/apis/ajax/documentation/#ClientLocation
if you are trying to get The Street Address!
include both JS and MAP Api Key, keep all together from the wizard
my code look like this: (use also a bit of jQuery)
var geocoder = null;
var lat = null;
var lng = null;
$(function() {
if (GBrowserIsCompatible()) {
if (google.loader.ClientLocation &&
// i used this here cause not always
//this retrieve the correct LAT & LON
// so set it manually
google.loader.ClientLocation.address.country_code == "IT" ) {
lat = google.loader.ClientLocation.latitude;
lng = google.loader.ClientLocation.longitude;
} else {
//alert( 'Insert Your Latitude & longitude manually!' );
lat = '42.464826';
lng = '14.214095';
}
//creat the full LAT + LON
points = new GLatLng( lat , lng );
//get the Street Address
get_address(points);
}
});
function get_address(latlng) {
if (latlng) {
geocoder = new GClientGeocoder();
geocoder.getLocations(latlng, function(addresses) {
if(addresses.Status.code != 200) {
alert("reverse geocoder failed to find an address for " + latlng.toUrlValue());
}
else {
address = addresses.Placemark[0];
var myHtml = address.address;
$('#address').text(myHtml);
}
});
}
};
peraphs read this link may help too:
Get street address at lat/long pair
If you need something more precise than IP geolocation, you could use the W3C Geolocation API in supported browsers (notably, Firefox 3.5 and Mobile Safari) to request the user's latitude and longitude and then use Google's client-side reverse geocoding service to guess the user's approximate street address. (Code samples for both of those steps included on my test page.)
If you go this route, be sure to explain to your users up front why you're requesting their location and how you're using their information (e.g. that you're not storing it until they actually submit a form) because it's technically required by the API and because some users will be creeped out by how easily you can guess their street address.
Yes it is possible achieve using html 5 and Google API 3, in the given code you have to change your APIKey and map-canvas is a element in the html body
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=yourAPIKey&sensor=false"></script>
<script type="text/javascript">
var lat;
var lng;
function initialize() {
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position)
{
lat = position.coords.latitude;
lng = position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat, lng);
var myTittle = "My Current Location! Lat: " + lat + "lng: " + lng;
var marker = new google.maps.Marker({
position: myLatlng,
title: myTittle
});
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I was looking to find how to map the current location and a destination location. To achieve this here is what I did:
Note* replace: YOUR_DESTINATION_ADDRESS with an address in a format like: "147+Wyndham+Street+N+,+Suite+206,+Guelph,+On,+N1H+4E9"
<div id="Map" style="width: 100%; height: 600px;"> </div>
<script type="text/javascript">
$(function(){
var zoom = 11;
function success(position) {
var LAT = position.coords.latitude;
var LONG = position.coords.longitude;
$('#Map').append('<p>Current Latitude: ' + LAT + '<br/>Current Logitude: ' + LONG +'<br/><br/>Note* This may not display your exact location, but just your city. Works better on mobile devices</p>');
var map = '<iframe style="width: 100%; height: 600px;" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.ca/maps?source=s_d&saddr=' + LAT +',+' + LONG +'&daddr=**YOUR_DESTINATION_ADDRESS**&ie=UTF8&t=hz=' + zoom + '&output=embed"></iframe>';
$('#Map').append(map);
}
function error(){
/*Error Code*/
}
function MakeMap(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
}
}
MakeMap();
});
</script>
Related
I got one console error when i try to run the code in my temp server "[Deprecation] getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS".
in my header am linking the script tag.
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBlS6vRUDeM0XdliZ4iWDyDMekH45wYcck&libraries=places" type="text/javascript"></script>
Get your current position:
Click here
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
document.getElementById("start").value = "";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
document.getElementById('cityLat').value = position.coords.latitude;
document.getElementById('cityLng').value = position.coords.longitude;
}
</script>
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var bangalore = new google.maps.LatLng(12.9716, 77.5946);
var myOptions = {
zoom:12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: bangalore
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
var startLat = document.getElementById('cityLat').value;
var startLong = document.getElementById('cityLng').value;
var endLat = $('select.end').find(':selected').data('lat');
var endLong = $('select.end').find(':selected').data('long');
/*alert(startLat+"---"+startLong+"---"+endLat+"---"+endLong);*/
if(startLat && startLong){
var start = new google.maps.LatLng(startLat, startLong);
}else{
var start = document.getElementById("start").value;
}
var end = new google.maps.LatLng(endLat, endLong);
var distanceInput = document.getElementById("distance");
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);
distanceInput.value = response.routes[0].legs[0].distance.value / 1000;
}
});
}
</script>
when i run the above code snippet in my local system i getting the map correctly.
when i move the code to testing server am getting the console error "[Deprecation] getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS"
I tried without https the script tag source link.
Anybody could you please give me a suggestion for this ?
Thank you.
You need to install SSL Certificate. There is no quick fix for this solution. Google Chrome and other browsers are blocking this for security reasons.
Chrome has disallowed the usage of getCurrentPosition() for websites without SSL.
Google Maps API could solve this but its usage limits is way low.
I dont understand, how could this happen? I only got 1 variable but it seems like it has 2 different values. Please see the output below. Here's the code of the webpage:
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
var map;
var geocoder;
var center = new google.maps.LatLng(11.17840187,122.59643555);
var marker = new google.maps.Marker();
var info = new google.maps.InfoWindow();
var latitude = 0.00;
var longitude = 0.00;
var address = "NO ADDRESS";
var loaded = false;
function initialize() {
var mapProp = {
center : center,
zoom : 5,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
geocoder = new google.maps.Geocoder();
google.maps.event.addListener(map, "click", function (event) {
latitude = event.latLng.lat();
longitude = event.latLng.lng();
center = new google.maps.LatLng(latitude,longitude);
displayAddress();
moveToCenter();
console.log("Address : " + address)
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function moveToCenter(){
map.panTo(center);
marker.setPosition(center);
marker.setMap(map);
}
function displayAddress(){
geocoder.geocode( {'latLng': center},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if(results[0]) {
address = results[0].formatted_address;
}
else {
address = "";
}
info.setContent("<b>" + address + "</b>");
info.open(map,marker);
}
});
}
function setWidth(width){
document.getElementById('googleMap').style.width = width + "px";
google.maps.event.trigger(map, 'resize');
}
function setHeight(height){
document.getElementById('googleMap').style.height = height + "px";
google.maps.event.trigger(map, 'resize');
}
</script>
<style>
body
{
padding : 0;
margin : 0;
overlow : hidden;
}
#googleMap
{
width : 600px;
height : 600px;
overlow : hidden;
}
</style>
</head>
<body>
<div id="googleMap"></div>
</body>
</html>
I have a variable address in my code, but I dont understand why it has two different values. How does this happen? Is it a Javascript Bug?
Here's the output:
I see what you're asking now. Perhaps we can we rephrase the question.
Q: Why when I set address in displayAddress() does it display the address correctly in the map but still log "No address" in the console?
A: It's because you've introduced an asynchronous process into your code.
You think that the following should happen:
Set address to "No address"
Call displayAddress() which changes the value of address and
also displays it on the map
Log the changed address
What's actually happening is this:
Set address to "No address"
Call displayAddress() - the async process geocode starts
Log the address (this hasn't changed)
The async operation completes and the address is displayed on the map.
If you want to know more about async processes and how to return values from them this SO question has lots of relevant information.
I think the problem comes from the fact that the code which modifies your address variable is called after the console.log instruction.
As a matter of fact, all of the following code:
if(status == google.maps.GeocoderStatus.OK) {
if(results[0]) {
address = results[0].formatted_address;
}
else {
address = "";
}
info.setContent("<b>" + address + "</b>");
info.open(map,marker);
}
is contained in the callback function which is passed to the geocoder.geocode method, and which will then be executed once the remote request has been completed. Which, given the reponse time of the remote request (a few tens or hundreds of miiliseconds), occurs after the execution of the console.log statement.
Take a closer look at your code.
function displayAddress(){
geocoder.geocode( {'latLng': center},
function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
if(results[0]) {
address = results[0].formatted_address; <------ Take a look at this
}
else {
address = "";
}
info.setContent("<b>" + address + "</b>");
info.open(map,marker);
}
});
}
I'm using random user generator to get the JSON data:
http://randomuser.me/
I make a call everytime I click a button, so the zip code I get in return I use it to do a geocoder in google maps API and get a latitude and longitude. Until that it has work very well but I don't know how to use it on Google Maps. I'm trying to create D3 circles and there are two ways to do this:
1.- Using the drawing shapes from Google Maps API:
https://developers.google.com/maps/documentation/javascript/shapes#circles
2.- Using the custom overlay from Google Maps API:
https://developers.google.com/maps/documentation/javascript/customoverlays
I need to do it with the overlay and draw the graphics with D3 like in this example:
http://bl.ocks.org/mbostock/899711
So my doubts are:
1.- How can I use D3 to use the latitude and longitude and load them? In the example they load JSON from the directory but here I'm using remote data. Should I considered a JSON parse or a String or any other?
2.- What is the correct way to write this as a clean code? And why?
Thank you in advance
index.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/d3.v3.js"></script>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(16.4706001, -33.6728973),
zoom:3,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
<div id="button">
<button id="loadbutton">Click to Load</button>
</div>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
script.js
var randomuserURL = 'http://api.randomuser.me/';
var myButton = document.getElementById('loadbutton');
myButton.onclick = loadAJAX;
var lat = '';
var lng = '';
var zipcode;
var geocoder = new google.maps.Geocoder();
function loadAJAX () {
$.ajax({
url: randomuserURL,
dataType: 'json',
success: function(data){
zipcode = data.results[0].user.location.zip;
latlng();
}
});
}
function latlng () {
geocoder.geocode( { 'address': zipcode}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
console.log('Latitude: ' + lat + ' Logitude: ' + lng);
}
You basically have everything you need.
There's no need to load a "local" file -- d3.json will take any URL as its first argument. The only problem you may run into are browser security restrictions. In that case JSONP may help.
If your code works for you, it should be fine. Honestly, you have so little code that it really doesn't matter.
I am working on a migration project from google maps V2 to V3 and wrote the bellow code but
getting error and unable to solve the problem.
Am i using wrong method of google maps?
What is wrong in this code?
<div id="map_canvas" style="width: 300px; height: 225px; font-family:arial; font-size:10px;"></div>
<?php
$map = getMap();
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
function getMap()
{
$mapKey = 'MYKEY';
$_script = '
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?key='. $mapKey .'&sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
// call initialize function
initialize( $_ADDRESS );
// initialize map
function initialize()
{
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
// call show Address
showAddress( address );
}
// show address
function showAddress(address)
{
if (geocoder)
{
geocoder.getPosition( address, function(point)
{
if (!point)
{
alert(address + " not found");
}
else
{
map.setCenter(point, 13);
var marker = new google.maps.Marker(point);
map.addOverlay(marker);
//marker.openInfoWindowHtml(address);
}
});
}
}
//]]>
</script>';
return $_script;
}
?>
Any idesa?
Thanks
I have split these answers as the first deals with the fundamentals of the javascript, this then deals with using the Google Maps API.
As I've never used the maps API, I can't comment on V2, but looking at how you do things in V3, I think this does what you're looking for...
<div id="map_canvas" style="width: 300px; height: 225px; font-family:arial; font-size:10px;"></div>
<?php
$map = getMap();
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
function getMap()
{
$mapKey = 'MYKEY';
$_script = '
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var geocoder = null;
// call initialize function
initialize( "$_ADDRESS" );
// initialize map
function initialize( address )
{
map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
geocoder = new google.maps.Geocoder();
// call show Address
showAddress( address );
}
// show address
function showAddress(address)
{
if (geocoder)
{
geocoder.geocode( { "address": address }, function( results, status )
{
if ( status == google.maps.GeocoderStatus.OK )
{
position = results[0].geometry.location;
map.setCenter(position, 13);
var marker = new google.maps.Marker({ map: map, position: position });
}
else
{
alert(address + " not found");
}
});
}
}
//]]>
</script>';
return $_script;
}
?>
Having said that, I'd question the str_replace straight into the javascript - can you trust the source of that data? If not, then you should look up how to sanitise that string before you put it into your javascript or you may allow people to inject code into your site.
Looking at the fundamental javascript issues you have...
Try adding quotes around the string that you're replacing into the javascript
echo $map = str_replace('$_ADDRESS', 'MYADDRESS', $map );
Becomes:
echo $map = str_replace('$_ADDRESS', "'MYADDRESS'", $map );
That way the string that contains the address in javascript is properly quoted.
Also, ensure that you can receive the address in your initialize function:
function initialize()
Becomes:
function initialize( address )
Finally, do not redeclare "map" when you assign it a value in "initialize", otherwise you are referencing a different variable that only exists in that function:
var map = new google.maps.Map(document.getElementById("map_canvas"), {
Becomes:
map = new google.maps.Map(document.getElementById("map_canvas"), {
I'm using the Google Maps API (v2) and would like to center the map onload to a country (for example england).
At the moment i center the map using:
map.setCenter(new GLatLng( 43.907787,-79.359741), 9);
But this obviously requires longitude and Latitude.
Any way to do this by inserting a name of a country?
var country = "United States"
var map = new GMap2($("#map")[0]);
map.setUIToDefault();
var geocoder = new GClientGeocoder();
geocoder.getLatLng(country, function (point) {
if (!point) {
// Handle error
} else {
map.setCenter(point, 8, G_PHYSICAL_MAP);
}
});
You need to geocode the address first:
var geocoder = new google.maps.Geocoder();
var location = "England";
geocoder.geocode( { 'address': location }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
} else {
alert("Could not find location: " + location);
}
});
Turning a location name or address into a latitude/longitude like this is called geocoding. Google Maps API now includes this capability: see http://code.google.com/apis/maps/documentation/services.html#Geocoding
They include a sample application where you can type in an address, and it does work to simply type a country name. I don't know if they are going to the exact center of the country.