Center google map on kml, not location - javascript

I have this simple script on a web page, loading a small kml file, but when I add geolocation, it always centers the map on the current location.
And I want to load the map centered on the kml file. User location should only be displayed if he is in the area of the kml, or if he drags the map to the area where he is located.
Accessorily, is there a way to easily refresh the user location on the map with javascript (maps api 3), without re-centering the map ?
var map;
function initialize() {
var centre = new google.maps.LatLng(4,4);
var mapOptions = {
zoom: 11,
center: centre
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'http://www.server.com/kmlfile.kml',
preserveViewport: false
});
ctaLayer.setMap(map);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
// map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
So, here is my latest update, I added the disableAutoPan: true option to infoWindow, as indicated, and to refresh the user position I used watchPosition in place of getCurrentPosition, together with setPosition to move theinfoWindow position :
var map;
function initialize() {
var center_map = new google.maps.LatLng(45,-4);
var mapOptions = {
zoom: 11,
center: centre
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'http://www.server.com/kmlfile.kml', preserveViewport: false
});
var ctaLayer.setMap(map);
if(navigator.geolocation) {
navigator.geolocation.watchPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
if(typeof infowindow == "undefined") {
infowindow = new google.maps.InfoWindow({
disableAutoPan: true,
map: map, position: pos,
content: 'Your position',
zIndex: 0 /* not needed */
});
}
else {
infowindow.setPosition(pos);
}
}, function() {
/*handleNoGeolocation(true);*/
/* had to delete this because errors centered the map on North Pole */
},
{ timeout: 10000, enableHighAccuracy: true }); /* high accuracy for tests */
}
};
google.maps.event.addDomListener(window, 'load', initialize);
Apparently it works although I suppose it's quite raw...

When you open the InfoWindow it is panning the map to display it. Set disableAutoPan to true in the InfoWindowOptions.
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.',
disableAutoPan: true
});
proof of concept fiddle
code snippet:
var map;
function initialize() {
var centre = new google.maps.LatLng(4, 4);
var mapOptions = {
zoom: 11,
center: centre
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'http://www.geocodezip.com/geoxml3_test/cta.xml',
preserveViewport: false
});
ctaLayer.setMap(map);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
disableAutoPan: true,
map: map,
position: pos,
content: 'Location found using HTML5.'
});
// map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content,
disableAutoPan: true
};
var infowindow = new google.maps.InfoWindow(options);
// map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>

Related

Plotting google maps with local storage

I have created an application that allows a user to plot a flag on google maps upon a click event although once the page is refreshed all of flags are lost. I want to be able to keep the data the user has input using local storage, can anyone point me in a direction or show me sample code of how they would handle this problem? thanks.
Basic google maps code without local storage
var map;
var myCenter=new google.maps.LatLng(54.906435, -1.383944);
function initialize()
{
var mapProp = {
center:myCenter,
zoom:13,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
//creating the event for placing the marker
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
//Funcion to place the marker on the map (flag)
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
icon:'flag.png',
map: map,
});
//open information window once marker is placed
var infowindow = new google.maps.InfoWindow({
content: 'User has placed warning'
});
infowindow.open(map,marker);
//zoom into the marker
google.maps.event.addListener(marker,'click',function() {
map.setZoom(17);
map.setCenter(marker.getPosition());
});
}
google.maps.event.addDomListener(window, 'load', initialize);
This should do the trick ;)
function initialize()
{
var mapProp = {
center:myCenter,
zoom:13,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
//creating the event for placing the marker
google.maps.event.addListener(map, 'click', function(event) {
writeToStorage(event.latLng);
placeMarker(event.latLng);
});
setupStorage();
readFromStorage();
}
function setupStorage() {
if(typeof(localStorage) === "undefined") {
// If localStorage isn't supported, fake it.
// Won't persist between sessions.
localStorage = {};
}
localStorage.locations = localStorage.locations || [];
}
function writeToStorage(location) {
localStorage.locations.push(location);
}
function readFromStorage() {
localStorage.locations.forEach(function(location) {
placeMarker(location);
});
}
//Funcion to place the marker on the map (flag)
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
icon:'flag.png',
map: map,
});
//open information window once marker is placed
var infowindow = new google.maps.InfoWindow({
content: 'User has placed warning'
});
infowindow.open(map,marker);
//zoom into the marker
google.maps.event.addListener(marker,'click',function() {
map.setZoom(17);
map.setCenter(marker.getPosition());
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Let me know if you have any trouble understanding any of it.
var map = {};
var polyOptions = {};
$(document).ready(function () {
map = new google.maps.Map(document.getElementById('MapDiagram'), {
zoom: 5.4,
center: new google.maps.LatLng(40, -10),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: true
});
polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
});
map.setCenter(new google.maps.LatLng(coord1, coord2));

Markers on Google Maps API are not showing up with Geolocation

I am trying to have places come up on the map based on the users geolocation. I know the geolocation works and map shows up, but none of the markers come up showing the local businesses. I am not getting any errors in console as well. I made sure that the script in my html is passing both the library and the API key, but just in case, here is the script:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&key=MY_KEY"></script>
Here is my JavaScript...
var map;
var infowindow;
var service;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
mapTypeControl: false,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
scaleControl: true,
streetViewControl: false
});
// Start Geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Found You!'
});
var request = {
location: pos,
radius: 500,
types: ['store']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
// Callback for Places
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
// Create Marker for Places
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
// Google Maps Error Flags
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
Here is my updated coded that I got to work.. I made some customizations to the markers, but this works now. As mentioned in the comments, I believe the issue had to do with the variables set for infowindow. I changed the geolocation one to 'infowindowLocation' instead and adjusted in the error flags section.
var map;
var infowindow;
var service;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 13,
mapTypeControl: false,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_CENTER
},
scaleControl: true,
streetViewControl: false
});
// Start Geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindowLocation = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Found You!'
});
var request = {
location: pos,
radius: 3218.69,
types: ['dentist']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
// Callback for Places
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(results[i]);
}
}
}
// Create Marker for Places
function createMarker(place) {
var placeLoc = place.geometry.location;
var image = 'img/flag.png';
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
title: place.name,
animation: google.maps.Animation.DROP,
icon: image
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map,marker);
});
}
// Google Maps Error Flags
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindowLocation = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
initialize();

different colors for different routes on google maps importing multiple KML files build in google engine?

I am loading multiple KML layers files into google maps. However it becomes difficult to read since they are different Bus routes on the map. Is it possible to have them in different colors for example kml1 file to be in red , kml2 file to be in blue etc. I used google engine to build these KML files however i did not get an option to use different colors on the line/markers.
function initialize() {
var abby = new google.maps.LatLng(49.051078,-122.314221);
var mapOptions = {
zoom: 11,
center: abby
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url:'https://dl.dropboxusercontent.com/u/143598220/1.%20Blueridge-McKee%20GoLine.kml'
});
var ctaLayer2 = new google.maps.KmlLayer({
url:'https://dl.dropboxusercontent.com/u/143598220/2.%20Bluejay-Huntingdon%20GoLine.kml'
});
var ctaLayer3 = new google.maps.KmlLayer({
url:'https://dl.dropboxusercontent.com/u/143598220/3.%20Clearbrook%20-%20UFV%20GoLine.kml'
});
ctaLayer.setMap(map);
ctaLayer2.setMap(map);
ctaLayer3.setMap(map);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
disableAutoPan: true
});
marker=new google.maps.Marker({
position:pos,
animation:google.maps.Animation.BOUNCE,
disableAutoPan: true
});
marker.setMap(map);
var infowindow2 = new google.maps.InfoWindow({
content:"Your Current Location!"
});
google.maps.event.addListener(marker, 'click', function() {
infowindow2.open(map,marker);
});
// map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);

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;

Uncaught ReferenceError: pos is not defined

js:
var map;
function initialize() {
$('#refreshmap').on('click',initialize);
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(-29.3456, 151.4346),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
var marker = new google.maps.Marker({
position: pos,
title: 'Position',
map: map,
draggable: true,
visible:true
});
updateMarkerPosition(pos);
geocodePosition(pos);
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerPosition(marker.getPosition());
});
$('#button').click(function(){
marker.setVisible(true);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html:
<div id="map-canvas"></div>
<button type="button" id="button" class="map_buttons button_style">Add marker</button>
The above code is for display marker on current location by clicking a button.Map is showing the current location but marker is not working.
I am getting this error in console "Uncaught ReferenceError: pos is not defined".
Try this:
var map;
var pos;
function initialize() {
$('#refreshmap').on('click', initialize);
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Try HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(-29.3456, 151.4346),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
var marker = new google.maps.Marker({
position: pos,
title: 'Position',
map: map,
draggable: true,
visible: true
});
updateMarkerPosition(pos);
geocodePosition(pos);
google.maps.event.addListener(marker, 'drag', function () {
updateMarkerPosition(marker.getPosition());
});
$('#button').click(function () {
marker.setVisible(true);
});
}
Basically, declare var pos in the global scope, and remove var while initializing pos
The issue is that
During creation of the marker object, pos is undefined in the scope
try to declare pos global, like your map
var map;
var pos;

Categories

Resources