setCenter doesn't seem to accept any objects i feed into it - javascript

I have been working on this for hours, but I can't seem to find the correct object feed into setCenter for this particular scenario:
var map,
currentPositionMarker,
mapCenter = new google.maps.LatLng(14.668626, 121.24295)
function initializeMap(){
map = new google.maps.Map(_('map'), {
zoom: 18,
center: mapCenter,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
}
function locError(error) { alert("current position not be found");}
function setCurrentPosition(pos) {
currentPositionMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
),
title: "Current Position"
});
map.panTo(new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
));
}
function displayAndWatch(position) {
setCurrentPosition(position);
watchCurrentPosition(position);
}
function watchCurrentPosition(pos) {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position
);
**map.setCenter(google.maps.LatLng(pos.coords.latitude,pos.coords.latitude));**
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
function initLocationProcedure() {
initializeMap();
infoWindow = new google.maps.InfoWindow({ maxWidth: 400 });
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
} else { alert("Geolocation API not supported"); }
}
(it's especially frustrating as I have to drive around the block to verify if each change works!).
Anyone know what I am doing wrong in the map.setCenter line above?

you have to set it like this:
map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));

Related

Google Map Marker not displaying

I've tried adding a marker variable to my Google Map API and it will not show. Any ideas why?
The website: http://www.franhaines.co.uk/paddlethewye/
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(51.843143, -2.643555),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
$("#findButton").click(findMe);}
function errorCallback() {
alert("I'm afraid your browser does not support geolocation.");
}
function successCallback(position) {
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), myOptions);
}
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"We are here!"
});
function findMe()
{
if (navigator.geolocation)
{
console.log(navigator.geolocation.getCurrentPosition(successCallback,errorCallback,{timeout:10000}));
}
else
{
alert("I'm afraid your browser does not support geolocation.");
}
}
the issues
myLatlng is not defined
you create the marker before the map has been created
even when the map already has been created the Map-instance(map) wouldn't be accessible in the scope where you create the marker
the geolocation-callback creates a new Map-instance, the marker will not be drawn in this instance
Fixed issues:
function initialize() {
var myLatlng = new google.maps.LatLng(51.843143, -2.643555),
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: myLatlng
}),
marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "We are here!"
});
//use the button as control when you want to
map.controls[google.maps.ControlPosition.TOP_CENTER].push($("#findButton")[0]);
function successCallback(position) {
var latlng = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude),
myOptions = {
zoom: 15,
center: latlng,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
},
bounds = new google.maps.LatLngBounds(latlng);
bounds.extend(marker.getPosition());
//only set new options for the map
//instead of creating a new instance
map.setOptions(myOptions);
//when you want to
//set the viewport of the map so that it diplays both locations
map.fitBounds(bounds);
//marker for the user-location when you want to
new google.maps.Marker({
position: latlng,
map: map,
title: "You are here!",
icon: 'http://maps.gstatic.com/mapfiles/markers2/boost-marker-mapview.png'
});
}
function errorCallback() {
alert("I'm afraid your browser does not support geolocation.");
}
function findMe() {
//hide the button, no need for further clicks
$(this).hide();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {
timeout: 10000
});
} else {
alert("I'm afraid your browser does not support geolocation.");
}
}
$("#findButton").click(findMe);
}
Demo: http://jsfiddle.net/doktormolle/eb6kwkwg/
There is another, CSS-related issue(you may have noticed that the apperenance of the controls is distorted). For a fix see: Google Map Infowindow not showing properly

Geolocation google maps jquery

I'm trying to do a script that locates the current position of the user and after reload of the page sets out a random coordinate. I can initilize the map and the random coordinate functions but the geolocation doesn't seem to locate my position, allthough it prints out the message in the infowindow?
var map;
var pos;
function initialize() {
//here is the starting for the map, where it will begin to show
var latlng = new google.maps.LatLng(59.2982762, 17.9970823);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
//geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: "You are here"
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
}
else {
handleNoGeolocation(false);
}
function handleNoGeolocation(errorflag) {
if (errorflag) {
alert('Geolocation not supported');
initialLocation = stockholm;
}
else {
alert('balblababa');
initialLocation = siberia;
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options, position);
}
//stop geolocation
var flagAreas = [
[59.2967322, 18.0009393],
[59.2980245, 17.9971503],
[59.2981078, 17.9980875],
[59.2982762, 17.9970823],
[59.2987638, 17.9917639],
[59.2987649, 17.9917824],
[59.2987847, 17.9917731],
[59.2988498, 17.991684],
[59.2988503, 17.9981593],
[59.3008233, 18.0041763],
[59.3014033, 18.0068793],
[59.3016619, 18.0137766]
];
var random = flagAreas.sort(function() {
return Math.random() - 0.5 })[0];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(random[0], random[1]),
map: map,
});
}
window.onload = initialize;
</script>
Thanks to Suvi Vignarajah.
Here is the working code!
var map;
var pos;
function initialize() {
//here is the starting for the map, where it will begin to show
var latlng = new google.maps.LatLng(59.2982762, 17.9970823);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
//geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: initialLocation,
content: "You are here"
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
}
else {
handleNoGeolocation(false);
}
function handleNoGeolocation(errorflag) {
if (errorflag) {
alert('Geolocation not supported');
initialLocation = stockholm;
}
else {
alert('balblababa');
initialLocation = siberia;
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options, position);
}
//stop geolocation
var flagAreas = [
[59.2967322, 18.0009393],
[59.2980245, 17.9971503],
[59.2981078, 17.9980875],
[59.2982762, 17.9970823],
[59.2987638, 17.9917639],
[59.2987649, 17.9917824],
[59.2987847, 17.9917731],
[59.2988498, 17.991684],
[59.2988503, 17.9981593],
[59.3008233, 18.0041763],
[59.3014033, 18.0068793],
[59.3016619, 18.0137766]
];
var random = flagAreas.sort(function() {
return Math.random() - 0.5 })[0];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(random[0], random[1]),
map: map,
});
}
window.onload = initialize;

Geolocation: moving only google maps marker without reload the map

I need to update only the marker when the device is moving or when the device is getting more accuracy. When the position change also reload the map and I need to move only the maker. I have the following code:
if (navigator.geolocation) {
navigator.geolocation.watchPosition(
function(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
var coords = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: 20,
center: coords,
streetViewControl: false,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var capa = document.getElementById("capa");
capa.innerHTML = "latitud: " + latitude + " longitud: " + " aquesta es la precisio en metres : " + accuracy;
map = new google.maps.Map(
document.getElementById("mapContainer"), mapOptions
);
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "ok"
});
},function error(msg){alert('Please enable your GPS position future.');
}, {maximumAge:0, timeout:5000, enableHighAccuracy: false});
}else {
alert("Geolocation API is not supported in your browser.");
}
Thanks!
I believe that the problem is that you create a new map inside the watchPosition function. You only need to create one marker and then update its position inside the watchPosition function.
navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position
);
});
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
Maybe this example will help you:
<!doctype html>
<html lang="en">
<head>
<title>Google maps</title>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"></script>
<script type="text/javascript">
var map,
currentPositionMarker,
mapCenter = new google.maps.LatLng(40.700683, -73.925972),
map;
function initializeMap()
{
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 13,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function locError(error) {
// the current position could not be located
alert("The current position could not be found!");
}
function setCurrentPosition(pos) {
currentPositionMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
),
title: "Current Position"
});
map.panTo(new google.maps.LatLng(
pos.coords.latitude,
pos.coords.longitude
));
}
function displayAndWatch(position) {
// set current position
setCurrentPosition(position);
// watch position
watchCurrentPosition();
}
function watchCurrentPosition() {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position
);
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
} else {
alert("Your browser does not support the Geolocation API");
}
}
$(document).ready(function() {
initLocationProcedure();
});
</script>
</head>
<body>
<div id="map_canvas" style="height:600px;"></div>
</body>
</html>
one easy way to do is, simply call map.clearOverlays(); then read add new positions with map.addOverlay(<marker>)

google maps and geolocation with markers javascript

i want to make a google maps that shows the current location of the user and it should also be possible that the user can click on the map to add markers. i can do them separately but it fails when i try to combine them.
this is my code for the geolocation
function success(position) {
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '500px';
mapcanvas.style.width = '600px';
document.querySelector('article').appendChild(mapcanvas);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var options = {
zoom: 15,
center: coords,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcontainer"), options);
var marker = new google.maps.Marker({
position: coords,
map: map,
title:"You are here!"
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
and this is my code to add markers to the map.
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
map.setCenter(location);
}
check out the folllowing link..the example in it will help you surely.worked for me too.
http://www.codeproject.com/Articles/291499/Google-Maps-API-V3-for-ASP-NET

Show Button On Google Marker Drag

I wonder whether someone may be able to help me please.
I am using the code below to reverse geocode address details, in this case starting off with the OS Grid Ref.
Could someone perhaps tell me please how I would go about including code which upon the marker being dragged, a button called 'regenerateosgridref' would appear on the form.
(function reversegeocodeosgridref() {
var map, geocoder, latlng, marker;
window.onload = function() {
var myOptions = {
zoom: 6,
center: new google.maps.LatLng(54.312195845815246, -4.45948481875007),
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_RIGHT
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN,
position: google.maps.ControlPosition.TOP_LEFT
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
}
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
var form = document.getElementById('searchforlocationosgridref');
form.onsubmit = function() {
var lat = document.getElementById('osgb36lat').value;
var lng = document.getElementById('osgb36lon').value;
var latlng = new google.maps.LatLng(lat, lng);
getAddress(latlng);
return false;
}
}
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
},
function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerAddress(str) {
document.getElementById('returnedaddress').value = str;
}
function getAddress(latlng) {
if (!geocoder) {
geocoder = new google.maps.Geocoder();
}
geocoder.geocode({
'latLng': latlng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setCenter(results[0].geometry.location);
if (!marker) {
map.setZoom(16);
marker = new google.maps.Marker({
map: map,
draggable: true
});
}
}
marker.setPosition(results[0].geometry.location);
google.maps.event.addListener(marker, function() {
updateMarkerAddress;
});
google.maps.event.addListener(marker, 'dragend', function() {
geocodePosition(marker.getPosition());
document.getElementById('osgb36lat').value = marker.position.lat();
document.getElementById('osgb36lon').value = marker.position.lng();
var point = marker.getPosition();
map.panTo(point);
});
latLng = [marker.position.lat(), marker.position.lng()].join(', ');
geocodePosition(marker.getPosition());
document.getElementById('returnedaddress').value = results[0].formatted_address;
}
})
}
})();
Many thanks and kind regards
Chris
Add a line in your marker dragend event that will show the button.
In your dragend event:
document.getElementById('regenerateosgridref').style.display = 'block';
Rather than add another button to my form. I have added some Javascript code that will update the OS Grid Reference as the marker is being dragged.

Categories

Resources