Locate Current location marker - javascript

My code is to locate a current location marker for the user on google map by clicking on the button , geocode function will receive the address information .
how can i make the address take the current location value not the input value ?
http://jsfiddle.net/razanrab/WppF6/253/
<body>
<div id="panel">
<input id="city_country" type="textbox" value="Berlin, Germany">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="mapCanvas"></div>
<div id="infoPanel">
<b>Marker status:</b>
<div id="markerStatus"><i>Click and drag the marker.</i></div>
<b>Current position:</b>
<div id="info"></div>
<b>Closest matching address:</b>
<div id="address"></div>
</div>
</body>
//js
var geocoder;
var map;
var marker;
codeAddress = function () {
geocoder = new google.maps.Geocoder();
var address = document.getElementById('city_country').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 16,
streetViewControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
mapTypeIds:[google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.ROADMAP]
},
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
});

In order to get the current location from the user, you will need to use the geolocation API. Please see the documentation here:
https://developers.google.com/maps/documentation/javascript/geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
What you can do is use the variable above, pos, to set as the marker's location and the center of the map instead of the result of the geocode query like in your sample. This will center the map around the user's location instead of the location geocoded from the textbox.
I was able to use the JSFiddle you provided along with some code of my own and from our geolocation sample I linked above. I believe this is what you are looking for(Please be advised you will need to put your own API key into this JSFiddle for it to work) It will geolocate the user's position and allow the user to drag the marker and get address info just like in your sample. This will also allow the user to click the geocode button and still have the same functionality:
https://jsfiddle.net/45z4841z/1/
I hope this helps!

Related

Capture address using HTML5 Geolocation

I have this working code which is capturing a visitor's current location so I want it to display the visitor's current address into a textbox once the visitor accept to share the location
<div>
<input id="address" type="text" style="width:600px;"/>
</div>
<div id="map"></div>
<script>
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -13.961800, lng: 33.7693036},
zoom: 15
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=[MY API KEY HERE]&callback=initMap">
</script>
In order to do so, you need to use another API of Google which is called Geocoding.
https://developers.google.com/maps/documentation/geocoding/start?hl=fr
Indeed, you'll only retrieve GPS Coords with the geolocation API which is just 2 numbers.
Thanks to reverse geocoding, you can retrieve physical adress of the user with the coords X & Y.
Hope it'll help you out !

Google Maps Javascript map center update

All,
I am by no means a JavaScript programmer, mostly reusing/re-purposing snippets from here and there to accomplish things. I'm currently trying to work around a Google maps limitation, which is that the maps aren't styleable (AFAICT) unless you roll your own. I have a working HTML page, which contains a Google map, which correctly uses the Google maps styles and geolocation to set the map center to the user's location.
My question:
How can I keep the map centered on the user's location if their location changes while the page is open?
Search as I may I have been unable to find an example where the geolocation is updated through JavaScript. It could be that this isn't possible, it could be that Google's API documentation is weak, or possibly my Google-fu stinks. Possibly all three.
My code (taken almost verbatim from the Google Maps docs):
<body>
<div id="map"></div>
<script>
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 38.391677, lng: -97.661646},
zoom: 17,
styles: [...]
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=********************************&callback=initMap">
</script>
</body>
To detect changes in geolocation you can use the watchPosition method. (Not supported in all browsers though).
You can then call setCenter when you have a new set of co-ordinates, and it will centre the map for you.
There's a blog post here that seems to describe exactly what you are trying to do.
Assuming the initial setting of the center to the current location works, you could simply wrap the code in a setInterval call to repeatedly set the center every few seconds:
if (navigator.geolocation) {
setInterval(function() {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
}, 1000); // 1000 = number of milliseconds after which to repeat the call, i.e. 1 second
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
I'm not sure, if you really want the infoWindow and error message to be displayed on every call, but the basics are there.

Google maps API & HTML5 geolocation, map.getCenter() giving wrong value

I'm trying to write the users current location to a database but after the HTML 5 geolocation I get the wrong value for map.getCenter(). Here's the relevant code (from 2 different Google development sites). The complete code can be found at https://aslett.net/gmaps.
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 17,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
var latlng = map.getCenter();
var url = "add_marker.php?lat=" + latlng.lat() + "&lng=" + latlng.lng() + "&type=red";
downloadUrl(url, function(data, responseCode) {
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
The problem is the line (near the bottom)...
var latlng = map.getCenter();
...I was expecting it to give me the co-ordinates that were set in the HTML5 geolocation line (4 lines up)...
map.setCenter(pos);
...but it gives me the value that was set by (near the top)...
center: new google.maps.LatLng(47.6145, -122.3418),
I also tried to get the position using...
var latlng = infoWindow.getPosition();
... but that didn't work (am new to this map stuff and am grabbing at straws).
The line var latlng = map.getCenter();, which you have added to Google's example code on https://developers.google.com/maps/documentation/javascript/examples/map-geolocation, is executed BEFORE the getCurrentPosition() function. So at that time this variable is set, the map's center is still where you have defined it at the top. After that, the getCurrentPosition() method is fired.
You should add your extra lines of code into the getCurrentPosition() function.

Showing a Google Maps marker using JavaScript

I can't seem to add a markers to my maps. I am using Google Maps v.3 and Ruby on Rails.
Here's my JavaScript:
<script type="text/javascript">
var map;
function initialize()
{
var lat, lon, myOptions;
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
lat = position.coords.latitude;
lon = position.coords.longitude;
myOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
},
function(error)
{
alert('Error: An error occur while fetching information from the Google API');
});
}
else
{
alert("Your browser doesn't support geolocations, please consider downloading Google Chrome");
}
}
// Function for adding a marker to the page.
function addMarker(lat, lng) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map
});
}
</script>
Here is the HTML page and how I call it:
<div id="maps">
<div id="map_canvas" style="width:100%; height:400px">
</div>
<script type="text/javascript">
initialize();
addMarker(46.4352,-80.9455);
</script>
It's because addMarker() is being called before initialize() has finished.
initialize() needs to wait for a response from the geolocation api which means the map isn't initialized when you try and create the marker.
If you wrap addMarker inside callback and pass that to the initializing function which calls the callback function once a response is received then it should work as expected.
initialize(function() {
addMarker(46.4352,-80.9455);
});
function initilize(callback) {
navigator.geolocation.getCurrentPosition(function(position) {
// set up the map
callback();
});
}

Google maps into website based on user info

So i checked out all the relating posts. I was wondering, which i have yet to be able to find with about 20 google searches and about 45 website visits, if it is possible, based on users information that i could load a google map to display the users desired location.
Your probably asking, "Give me more details, that could mean anything!"
Your right, it could. So say i have a user that gives me (i got it from the database)
var stuffIGotFromMyWebServerWithPHPandMySQL = {
myComment: "Hey Everyone, party at my place!",
country: "US",
state: "MT",
city: "Bozeman",
address: "Emerson Cultural Center"
};
Now that i have the information of what city/state/country the event is in, and the name of a place, The Emerson is a real place in bozeman that google maps will recognize, is there a way to load a map with a marker at that location? I have the latitude/longitude for bozeman, MT, but i do not have such information about the Emerson. Is there a way i could provide the just the words, and have it bring up the place with a marker, on a static, no user interaction allowed map?
and i would probably want to load it through js
Thanks,
Michael B Paulson
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script>
var marker;
function initialize() {
var geocoder = new google.maps.Geocoder();
geocoder.geocode(
{
'address': 'Emerson Cultural Center, Bozeman, MT'
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 6,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
marker = new google.maps.Marker({
map:map,
draggable:false,
animation: google.maps.Animation.BOUNCE,
position: results[0].geometry.location
});
}
}
);
}
</script>
<div id="map_canvas" style="height:300px;width:300px"></div>
try this code and see if helps, you can use the Geocoder fro the google maps api to convert text to latlang.
you can see the following example from the documentation here http://code.google.com/apis/maps/documentation/javascript/examples/geocoding-simple.html

Categories