Displaying unknown coordiates and present location on same map - html

I am trying to display latitude and longitude coordinates on a map. This works fine but once this is displayed I also want to display the users current location on the same map while displaying the other position as well. Could someone please tell me how that is done. This is what I use to display the Lat and Longitude.
function showPosition()
{
//var latlon=position.coords.latitude+","+position.coords.longitude;
var lat = document.getElementById("saved_lat").value;
var lon = document.getElementById("saved_lon").value;
var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
+ lat + "," + lon +"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML="<img src='"+img_url+"'>";
}

First, you will need to get the user's current lat/lng position. Then you will need to use the 'markers' parameter in the static map to show two markers, one for the saved position and one for the user's position.
You can get a description on how to use markers here:
https://developers.google.com/maps/documentation/staticmaps/?csw=1#MarkerLocations
Below is a working modification of your code. Here's some tips:
I hardwired the saved_lat/lon values in the statements for demo'ing purposes. You will need to replace these or use your own HTML code.
The user's coordinate are obtained form the HTML geolocation method navigator.geolocation. This method will pass the lat/lon of the user's location to the ShowPosition() function.
I updated your ShowPosition() function:
A. Take the user's lat/lon as parameters
B. Added variable 'markers' to set two markers (saved and user's) in the google static map.
C. Added variable 'zoom' to set the zoom level.
<script>
// Get User's Coordinate from their Browser
window.onload = function () {
// HTML5/W3C Geolocation
if ( navigator.geolocation )
navigator.geolocation.getCurrentPosition( UserLocation );
// Default to Washington, DC
else
ShowPosition( 38.8951, -77.0367 );
}
// Callback function for asynchronous call to HTML5 geolocation
function UserLocation( position )
{
ShowPosition( position.coords.latitude, position.coords.longitude );
}
function ShowPosition( user_lat, user_lon )
{
var lat = document.getElementById("saved_lat").value;
var lon = document.getElementById("saved_lon").value;
var markers = "&markers=color:blue|label:S|" + lat + "," + lon + "|" + user_lat + "," + user_lon;
var zoom="&zoom=11";
var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
+ lat + "," + lon +"&size=400x300&sensor=false" + zoom + markers;
document.getElementById("mapholder").innerHTML="<img src='"+img_url+"'>";
}
</script>
<body>
<div id="mapholder"></div>
<input type="hidden" id="saved_lat" value="45.65"/>
<input type="hidden" id="saved_lon" value="-122.45"/>
</body>

Related

HTML5 Geo Location pass Lat and Lon to PHP page

I have a small piece of code which i want to collect the lat and lon co ordinates and then passes them to a php page.
However the code doesn't seem to be passing the variables to the php page.
Below is the code, any suggestions would be much appreciated.
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
var lat = position.coords.latitude;
var lon = position.coords.longitude;
document.location = "test1.php?lat=" + latitude + "&lon=" +
longitude;
});
}
Thanks
Lee
It looks like there's a simple variable name mismatch. You define lat and lon but use latitude and longitude on the next line. Try changing them to be the same pair.

Save current geolocation to variable

How can I save lat and lng values to variables using HTML5 geolocation API?
This is my code, copied from w3schools. How can I save coordinates to variables like var x= position.coords.latitude; and var y= position.coords.longitude; instead of just showing the values like the code is doing right now? I am beginner with javascript so I don't know how to do this
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Try It</button>
<script>
var x=document.getElementById("demo");
window.onload = function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.watchPosition(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;
}
</script>
</body>
</html>
And in my application I need to send values of those variables to server every minute. Would it be better to do the geolocation with watchposition or execute function that does getcurrentposition every minute?
Adding them to variables is as easy as:
var lat = position.coords.latitude;
var lon = position.coords.longitude;
OR as an object:
var coords = {lat: "", lon: ""};
Then to use the object in your code:
function showPosition(position)
{
coords.lat = position.coords.latitude;
coords.lon = position.coords.longitude;
x.innerHTML="Latitude: " + coords.lat +
"<br />Longitude: " + coords.lon;
}
As for sending the variables to a server this depends on what your serverside technology is but you will find many examples on google.
function sendToServer(){
// here you can reuse the object to send to a server
console.log("lat: " + coords.lat);
console.log("lon: " + coords.lon);
}

Google Maps geocode: undefined latitude

Hitting a page with the follow script displays:
lat: undefined
lon: 51.5001524
Why is it that while lat is undefined, lon is not?
A working example can be found here.
Pull up your web console and see for yourself!
$(document).ready(function(){
var geocoder;
function codeAddress()
{
geocoder = new google.maps.Geocoder();
var address = 'London, England';
geocoder.geocode({'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
lat = results[0].geometry.location.Ia;
lon = results[0].geometry.location.Ja;
console.log("lat: " + lat);
console.log("lon: " + lon);
}
});
}
codeAddress();
});
</script>
</head>
<body>
</body>
</html>
While we're at it - what is the historical significance of Ia and Ja? I presume it relates to the Cartesian unit vectors i and j (predominately used in Engineering) though I'm not sure.
I found other examples online who use .lat for .Ia and .lng for .Ja
These, however, are returning in the console:
function () {
return this[a];
}
Just need a kick in the right direction.
Thank you.
I would use lat() and lng():
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
This is a designed behaviour of the geocoder: google shifts the identifiers in
geometry.location.Ia;
geometry.location.Ja;
on a weekly basis, i.e. from above to
geometry.location.Ja;
geometry.location.Ka;
and so on, so it is not possible to refer by id to the geocoder result object.
Chances are Google are using a javascript minifier (e.g. http://jscompress.com/) which renames all variables - hence they're subject to change on every build.

How come my setCenter doesn't work?

I'm trying to get my map to re-orient to a new center when a user
chooses a district within the main map from a dropdown menu. See the
map here: http://bilware.net/BullyMap/BullyMap.html
I can get the zoom to change using map.setZoom (although it's
commented out below). But map.setCenter won't work. I thought it was
because I wasn't calling LatLng parameters correctly, but discovered
it won't work even if I plug in fixed parameters, as I think I've done
below.
I'm very new to this; any help is appreciated.
function changeMap() {
var selected_bully_table = $('#map_menu').val();
var searchString = document.getElementById('searchString').value.replace("'", "\\'");
if(searchString == "") {
layer.setQuery("SELECT 'geometry' FROM " + selected_bully_table);
return;
}
layer.setQuery("SELECT 'geometry' FROM " + selected_bully_table + " WHERE 'SDNAME' = '" + searchString + "'");
// Now zoom and center the map
{
map.setZoom(9);
myLatLng=(-91.9240850749,47.9119132072);
map.setCenter(myLatLng);
}
}
Replace
myLatLng=(-91.9240850749,47.9119132072);
with
myLatLng= new google.maps.LatLng(-91.9240850749,47.9119132072);
your latitude value should be between -90 degrees and +90 degrees and also you should pass a new instance of google.maps.LatLng class to the setCenter function.
A combination of the two other answers will give you your real answer.
The reason doing
myLatLng= new google.maps.LatLng(-91.9240850749,47.9119132072);
gives you a gray screen is because the position is outside of the bounds of the map. If you zoom out and scroll the map upwards you will see this :)
What you need to do is write
map.setZoom(9);
myLatLng = new google.maps.LatLng(LATITUDE,LONGITUDE);
map.setCenter(myLatLng);
and pass values of LATITUDE & LONGITUDE that are within the bounds of the map like (51, 0).

Customize Google Maps info window?

I'm working on a website of a client, a local church. I've embedded a Google Map using the Link feature on the Maps page. The info window on the map includes "Reviews," and the church is concerned about this. Is there a way to remove that from the info window? I don't want to remove any reviews themselves, just that link on the info window?
Is this possible? Are there any other customization options (besides the size) one can manipulate via the query string?
Nearly 2 years ago, I created a custom map with complete control over the contents of the bubble, using the API and some code manipulation. Click on the above link for a demo. I've cleaned up the code for this answer, although to implement you'll need to replace all YOUR__BLANK__HERE text with the appropriate values.
Step 1: Call the gMaps API
<script src="http://maps.google.com/maps?file=api&v=2&key=YOUR_API_KEY_HERE"
type="text/javascript">
</script>
Step 2: In the body of your document, create an element with id "map". Size and position it with CSS. It requires a height and width.
<div id="map" class="content"></div>
Step 3: After the div has been defined in the DOM, it is safe to insert the following script tag:
<script type="text/javascript">
//<![CDATA[
// Check to see if this browser can run the Google API
if (GBrowserIsCompatible()) {
var gmarkers = [];
var htmls = [];
var to_htmls = [];
var from_htmls = [];
var i=0;
// A function to create the marker and set up the event window
function createMarker(point,name,html) {
var marker = new GMarker(point);
// The info window version with the "to here" form open
to_htmls[i] = html +
'<br />Start address:<form action="http://maps.google.com/maps" method="get">' +
'<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
'<INPUT value="Get Directions" TYPE="SUBMIT">' +
'<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() +
// "(" + name + ")" +
'"/>';
// The inactive version of the direction info
html = html + '<br><a href="javascript:tohere('+i+')">Get Directions<'+'/a>';
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
gmarkers[i] = marker;
htmls[i] = html;
i++;
return marker;
}
// functions that open the directions forms
function tohere(i) {
gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}
// Display the map, with some controls and set the initial location
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(
YOUR_LATITUDE_HERE,
YOUR_LONGITUDE_HERE
),
YOUR_ZOOM_LEVEL_HERE // a value of 13 worked for me
);
// Set up one marker with an info window
var marker = createMarker(
new GLatLng(
YOUR_LATITUDE_HERE,
YOUR_LONGITUDE_HERE
),
'YOUR_MARKER_NAME_HERE',
'<i>YOUR_HTML_HERE<'+'/i>');
/* repeat the process to add more markers
map.addOverlay(marker);
var marker = createMarker(
new GLatLng(
YOUR_LATITUDE_HERE,
YOUR_LONGITUDE_HERE
),
'YOUR_MARKER_NAME_HERE',
'<i>YOUR_HTML_HERE<'+'/i>');
map.addOverlay(marker);*/
}
// display a warning if the browser was not compatible
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
// This Javascript is based on code provided by the
// Blackpool Community Church Javascript Team
// http://www.commchurch.freeserve.co.uk/
// http://www.econym.demon.co.uk/googlemaps/
//]]>
</script>
Using this code, the bubble contains the html you specify in YOUR_HTML_HERE plus a link to Get Directions, which (when clicked) turns into a textbox asking for a starting address. The result of the query, unfortunately, opens in a new browser window (since, at time of original publishing the API did not include directions capabilities)
I think I found the answer to my own question. The info window itself can't be modified, but by linking to the map for the address itself rather than the church as a business entity does the trick. The driving directions link is still there and that's mostly all they wanted.