I have been through every possible question related to my problem and tried many solutions, none seem to help. I am using the Map API of Google and the map is not centering to the correct lat long pair. It is pointing at (0,0) which is some where in the middle of South Pacific Ocean. Upon doing geolocation of my Lat Long pairs, it give the correct address.
Here is my code:
$(document).ready(function(){
var loc = {lat:0,long:0};
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}else{
alert("Geolocation is not supported by this browser.");
}
console.log(loc);
function showPosition(position){
loc.lat=position.coords.latitude;
loc.long=position.coords.longitude;
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(loc.lat, loc.long);
console.log(latLng);
if (geocoder) {
geocoder.geocode({ 'latLng': latLng}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].formatted_address);
alert('Address:'+results[0].formatted_address);
}else {
console.log("Geocoding failed: " + status);
}
}); //geocoder.geocode()
}
}
var latLong = new google.maps.LatLng(loc.lat, loc.long);
var mapOptions = {
center: latLong,
useCurrentLocation : true,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapMsg = new google.maps.Map(document.getElementById("local_map"), mapOptions);
google.maps.event.addDomListener(window, 'load');
var markerOptions = new google.maps.Marker({
clickable: true,
flat: true,
map: mapMsg,
position: latLong,
title: "You are here",
visible:true,
icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
});
});
Here is the screenshot of Firefox's console showing the correct Location address and lat long.
the First two Lines in the console are the Coordinates, the third line is the Geocoded location.
Please tell me where I'm wrong. I know this would be a silly mistake, but I'm new to it.
Regards
You never obtain the location from the geocoder result, or set the marker - and the order of execution is upside down (but does not fail)
Do this instead :
...
if (status == google.maps.GeocoderStatus.OK) {
var markerOptions = new google.maps.Marker({
clickable: true,
flat: true,
map: mapMsg,
position: results[0].geometry.location,
title: "You are here",
visible:true,
icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
});
var marker = new google.maps.Marker(markerOptions);
mapMsg.setCenter(results[0].geometry.location);
} else {
console.log("Geocoding failed: " + status);
}
...
Here is a somehow cleaned / working version of your code http://jsfiddle.net/zqeCX/
But you should really consider using one of the google map examples as a starting point, to get the execution flow right.
This is because navigator.geolocation.getCurrentPosition is async.
Therefore, when you do var latLong = new google.maps.LatLng(loc.lat, loc.long); the loc.lat is still '0', as is loc.long.
So you need to include does lines in your function showPosition.
Related
Using v.3 of the Google geocoder api with a Java back end, Velocity front end and an Oracle db.
Our current spec specifies that when a user selects a marker (lat/lng) that their zoom should be saved as well for future sessions. I can't for the life of me figure out how to do this. I have seen some information about bounds which I think I may be able to use in a hackey way, but I don't want to define the bounds of the map, I just want to save the zoom (like the lat/lng) and be able to pass it to the back end.
map.js
var geocoder;
var map;
var siteLocation;
var marker;
function initMap() {
var lat = parseFloat($("#newLat").val());
var lng = parseFloat($("#newLng").val());
geocoder = new google.maps.Geocoder();
siteLocation = { lat: lat, lng: lng };
map = new google.maps.Map(document.getElementById('map'),
{
center: siteLocation,
zoom: 19,
}
);
//set crosshair
console.log('setting waypoint marker');
crosshair = new google.maps.Marker(
{
position: siteLocation,
map: map,
draggable: false,
shape: { coords: [0, 0, 0, 0], type: 'rect' },
icon: "https://www.daftlogic.com/images/cross-hairs.gif"
}
);
crosshair.bindTo('position', map, 'center');
geocodeLatLng();
}
//use new selection to
function geocodeLatLng() {
var lat = crosshair.getPosition().lat();
var lng = crosshair.getPosition().lng();
var newLocation = crosshair.getPosition();
geocoder.geocode({ location : crosshair.position}, function(results, status) {
if (status == 'OK') {
results[0].geometry.location.lat();
results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
//get new user selected map options, [drop marker] (optional)
$("#addGeolocation").on("click", function (evt) {
geocodeLatLng();
evt.preventDefault();
var newZoom = map.getZoom();
var newLat = crosshair.getPosition().lat();
var newLng = crosshair.getPosition().lng();
$("#newLat").val(newLat);
$("#newLng").val(newLng);
newLocation = new google.maps.LatLng(newLat, newLng);
map.setCenter(newLocation);
map.setZoom(newZoom);
//make sure no marker exists
if ( marker !== undefined) {
marker.setPosition(newLocation);
} else {
marker = new google.maps.Marker({
position: newLocation,
map: map,
draggable: true
});
}
});
Velocity Macro
#macro(map $ADDRESS)
<script defer
src="https://maps.googleapis.com/maps/api/js?key=${GOOGLE_API_KEY}&callback=initMap">
</script>
<div id="map"></div>
<span class="innerBlock smallBlock" id="map" ></span>
<button type="button" onclick="geocodeLatLng()" id="addGeolocation"> $BTN_ADD_GEOLOCATION</button>
#inp_hidden("newLat" "$context.getSite().getLatitude()")
#inp_hidden("newLng" "$context.getSite().getLongitude()")
#inp_hidden("newZoom")
#end
I am completely stumped. Any ideas? Most of the solutions I have seen involve cookies but we cannot use those. Any advice would be appreciated. Thanks!
I think I understand what you mean but correct me if I'm wrong.
You could save the zoom level in a variable.
var zoom = 16;
and then save this in the local storage
localStorage.setItem("zoomLevel", zoom);
then use getItem method to retrieve it
var savedZoom = localStorage.getItem("zoomLevel");
So if you were planning to have the zoom levels in a select box or something, you can save the users choice into the local storage and then retrieve it when they return by setting to zoom to 'savedZoom' for example.
I'm not completely sure if this is what you were after but hopefully it helps. I've tried not to go into too much detail just incase it isn't.
In my project I have a google map, and I need to get markers on my map from database.
I have simple code like in example:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
google.maps.event.addListener(map, 'idle', function () {
getmarkers(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
This code works well, but it has one lack - it loads new markers only if user moves map.
But I need to load markers also if user is just sitting in front of computer and look on a map, not moving it.
I think the best way to do this is to use setInterval(getmarkers(map), 3000) but if I use it except where that function google.maps.event.addListener(... it can't find map. Are there any ways to solve this problem?
there are 2 issues,
setInterval expects the first argument to be a function(but it isn't, it's a function-call which will be executed immediately). Use a anonymous function to execute the statement:
setInterval(function(){getmarkers(map);}, 3000);
place the setInterval-call at the end of initialize to be sure that map is defined.
I have a Google Maps Application and I want to put custom Icons instead of the generic red icon that usually shows up. But no matter what I do I can not set a different icon it always shows up as the red one. I read that you can not have https in the url for icons so I uploaded it to an image host but I still can't get the icon to change. How do I get a custom icon on the map or do I have to go with bing?
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
function codeAddress() {
initialize();
var address = document.getElementById("address").value;
range = document.getElementById("distance").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
icon: "http://labs.google.com/ridefinder/images/mm_20_red.png"
position: results[0].geometry.location
});
lat1 = results[0].geometry.location.lat();
lng1 = results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
load();
}
Notice where it says:
icon: "http://labs.google.com/ridefinder/images/mm_20_red.png"
Not matter what I change that too it always shows the red generic icon.
You can load marker images over both HTTP and HTTPS on your page. However, you will want to make sure that the scheme matches the containing page's scheme (or at least, make sure that you use HTTPS if the page does too).
It seems you have typo in your MarkerOptions object: a missing comma after the icon string.
var marker = new google.maps.Marker({
map: map,
icon: "http://labs.google.com/ridefinder/images/mm_20_red.png",
position: results[0].geometry.location
});
I'm developing a web page with a Google Maps application and I'm having a little trouble with something. As it stands, the web page has a functional map (without any layers) and a search bar. I'm new to programming so hopefully there is a quick fix that I'm missing.
When I search an address, there is a placemark that is placed on the map. However, the map doesn't zoom into the placemark. How can I make the map zoom in for each searched address?
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder ();
var latlng = new google.maps.LatLng (55.1667, -114.4000);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
function codeAddress () {
var address = document.getElementById ("address").value;
geocoder.geocode ( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results [0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results [0].geometry.location
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
Thank you
I would call two functions:
(1) center the map on the marker
Either you already have the LatLng, or obtain it from marker.getPosition(), with it call map.setCenter(myLatLng).
(2) Set the zoom of the map
map.setZoom(zoomLevel), could be fixed around 12 to 16, or variable depending what kind of marker it is (street address or city overview?) This information can be stored in the marker variable, marker.zoomLevel.
function codeAddress () {
var address = document.getElementById ("address").value;
geocoder.geocode ( {'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({ map: map,
position: results[0].geometry.location });
map.setZoom(16);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
At the moment I serve pages showing a google map with a marker using an address retrieved from my database. I currently use a fairly simple piece of javascript code to add that marker by geocoding. My js code is dynamically generated by php. All is static except the "query" definition which gets initialized with the address search string.
I new to OSM and did some research to see if it can achieve this. At the moment I'm not sure it can. I found there are several js api's like OpenLayers which I'd need to use.
To sum it up :
How to add and show a single marker to an OSM, where the location is based on an address instead of a latitude/longtitude pair?
My current google based code is:
<script>
var geocoder; var map; var marker;
var query = 'Deutschland, Berlin, Platz der Republik 1, 11011';
function initialize()
{
var companyLocation = new google.maps.LatLng(51.964577109947506, 5.07568359375);
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = { zoom: 11, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
codeAddress();
}
function codeAddress()
{
var address = query;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: "Bundestag",
labelContent: "",
labelAnchor: new google.maps.Point(22, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {opacity: 0.75}
});
} else {
$('#map_canvas').html('<p style="margin: 15px">Address could not be found</p>');
}
});
}
</script>
See http://wiki.openstreetmap.org/wiki/Nominatim
Not going to write the code for you, but that wiki page has detailed information on how to call the Nominatim geocoding service.