I am building a Google Maps based web app on which I plot a moving dot of the user location. I am fetching continuously the user location from a server and would like to use the current user location when loading the map to center the window around it, meaning, when the user loads the site, the map will be centered around the first lat/long fetched from the server but enable the user to pan the map afterwards without re-centering it around where the user is. I was able to keep the map centered constantly around the user location but can't figure out how to use the first fetched location to center the map during initialization. My code is below, any help would be greatly appreciated. Thanks!
<script>
var locations = [
['location a', 37.771678, -122.469357],
['location b', 37.768557, -122.438458],
['location c', 37.755121, -122.438973],
['location d', 37.786127, -122.433223]
];
var map;
var i;
var marker;
var google_lat = 37.722066;
var google_long = -122.478541;
var myLatlng = new google.maps.LatLng(google_lat, google_long);
var image_dot = new google.maps.MarkerImage(
'images/red_dot.png',
null, // size
null, // origin
new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
new google.maps.Size( 8, 8 ) // scaled size (required for Retina display icon)
);
function initialize() {
var mapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
setMarkers(map, locations);
} //initialize();
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng1 = new google.maps.LatLng(beach[1], beach[2]);
marker = new google.maps.Marker({
position: myLatLng1,
icon: image_dot,
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script type="text/javascript">
var Tdata;
var image = new google.maps.MarkerImage(
'images/bluedot_retina.png',
null, // size
null, // origin
new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
new google.maps.Size( 17, 17 ) // scaled size (required for Retina display icon)
);
var userMarker = new google.maps.Marker({icon: image});
$.ajax({
method : "GET",
url: "get_location.php",
success : function(data){
Tdata=JSON.parse(data);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.get("get_location.php", function(Tdata) {
var JsonObject= JSON.parse(Tdata);
google_lat = JsonObject.lat;
google_long = JsonObject.long;
myLatlng = new google.maps.LatLng(google_lat, google_long);
userMarker.setPosition(myLatlng);
userMarker.setMap(map);
//map.setCenter(myLatlng); --> this is not what I want since it will always keep the map centerd around the user
});
}, 1000);
}
</script>
Only set the map center the first time. One way of detecting the first time would be to create the "userMarker" the first time the data is loaded.
var userMarker;
$.ajax({
method : "GET",
url: "get_location.php",
success : function(data){
Tdata=JSON.parse(data);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.get("get_location.php", function(Tdata) {
var JsonObject= JSON.parse(Tdata);
google_lat = JsonObject.lat;
google_long = JsonObject.long;
myLatlng = new google.maps.LatLng(google_lat, google_long);
if (!userMarker || !userMarker.setPosition) {
// create the marker
userMarker = new google.maps.Marker({
icon: image,
position: myLatlng,
map:map
});
// center the map the first time, when the marker is created
map.setCenter(myLatlng);
} else { // marker aleady exists
userMarker.setPosition(myLatlng);
}
});
}, 1000);
}
proof of concept fiddle
Related
I'm using the following JavaScript code to display Google Maps in my ASP.Net website. With this code I have added Google Places search that suggests results/places as the user types. I am displaying properties based on the searched location. However, I would like to display markers of the searched properties as well. I found a solution here: http://www.dotnetbull.com/2013/06/multiple-marker-with-labels-in-google.html but considering my limited knowledge of JavaScript I wasn't able to integrate it with my existing code to display places search along with markers on Google Maps. If you could please help me get it working I'll be thankful.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script type="text/javascript">
function LoadGoogleMAP() {
//Gets value of latitude and longitude of the search location from txtLatitude and txtLongitude textboxes.
var lat = document.getElementById('<%=txtLatitude.ClientID%>').value;
var lon = document.getElementById('<%=txtLongitude.ClientID%>').value;
var myLatlng = new google.maps.LatLng(lat, lon)
var markers = [];
var mapOptions = {
center: myLatlng,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
marker: true
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
// Create the search box and link it to the UI element.
var input = (document.getElementById('MainContent_txtSearch'));
map.controls[google.maps.ControlPosition.CENTER].push(input);
var searchBox = new google.maps.places.SearchBox((input));
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
map.setZoom(15);
});
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function () {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
</script>
Try this code from Official Google Doc:
function initialize() {
var markers = [];
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
map.fitBounds(defaultBounds);
// Create the search box and link it to the UI element.
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */(input));
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I am trying to plot on a google map a set of fixed markers and a marker for the user position. For these two sets of markers I would like to use a different image for the marker, however something weird is happening: when loading the page, the "fixed" markers get plotted properly but then immediately one disappears (the last one in the array) and then the user position shows up. In addition, the first fixed location gets the user location marker image, and the user positioning marker gets the image of the fixed markers. Ideally, the locations in the array will be plotted entirely (all 4) and with red_dot.png image on the marker, and the user positioning with the bluedot_retina.png on the marker.
It's really strange and I am struggling figuring out what is the root cause. Appreciate any help with this issue. thanks!
<script>
var locations = [
['location a', 37.60756088, -122.42793323],
['location b', 37.759736, -122.426957],
['location c', 37.752950, -122.438458],
['location d', 37.763128, -122.457942]
];
var map;
var i;
var marker;
var google_lat = 37.757996;
var google_long = -122.404479;
var myLatlng = new google.maps.LatLng(google_lat, google_long);
//google.maps.visualRefresh = true;
function initialize() {
var mapOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var image_dot = new google.maps.MarkerImage(
'images/red_dot.png',
null, // size
null, // origin
new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
new google.maps.Size( 8, 8 ) // scaled size (required for Retina display icon)
);
marker = new google.maps.Marker({
flat: true,
position: myLatlng,
icon: image,
optimized: false,
map: map,
visible: true,
title: 'I might be here'
});
setMarkers(map, locations);
} //initialize();
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng1 = new google.maps.LatLng(beach[1], beach[2]);
marker = new google.maps.Marker({
position: myLatLng1,
icon: image_dot,
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<script type="text/javascript">
var Tdata;
var image = new google.maps.MarkerImage(
'images/bluedot_retina.png',
null, // size
null, // origin
new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
new google.maps.Size( 17, 17 ) // scaled size (required for Retina display icon)
);
var userMarker = new google.maps.Marker({icon: image});
//var userMarker = new google.maps.Marker({icon: 'images/bluedot_retina.png'});
$.ajax({
method : "GET",
url: "get_location.php",
success : function(data){
Tdata=JSON.parse(data);
// console.log(data.lat);
console.log(Tdata.lat);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.get("get_location.php", function(Tdata) {
var JsonObject= JSON.parse(Tdata);
google_lat = JsonObject.lat;
google_long = JsonObject.long;
console.log(google_lat, google_long);
// $('#data').html('google_lat, google_long');
myLatlng = new google.maps.LatLng(google_lat, google_long);
//marker.setPosition(myLatlng);
userMarker.setPosition(myLatlng);
userMarker.setMap(map);
//map.setCenter(myLatlng);
});
}, 1000);
}
</script>
marker is a global variable. You are using it for both all of your locations and your user's position marker. Don't do that, assign unique (or local) names to the two classes of markers.
var Tdata;
var userMarker = new google.maps.Marker({icon: URL/to/custom/icon/for/user});
$.ajax({
method : "GET",
url: "get_location.php",
success : function(data){
Tdata=JSON.parse(data);
// console.log(data.lat);
console.log(Tdata.lat);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.get("get_location.php", function(Tdata) {
var JsonObject= JSON.parse(Tdata);
google_lat = JsonObject.lat;
google_long = JsonObject.long;
console.log(google_lat, google_long);
// $('#data').html('google_lat, google_long');
myLatlng = new google.maps.LatLng(google_lat, google_long);
userMarker.setPosition(myLatlng);
userMarker.setMap(map);
map.setCenter(myLatlng);
});
}, 1000);
}
I'm unsure how to explain this properly, but I basically want to display markers via Google API on a map and have a link on them to directions to that location. However, currently it only works if the user allows their location to be tracked.
What I want to do is to have basically those markers in both situations, where user does and does not allow their location to be tracked, but just the link would be changed.
So if the user allows their location to be tracked, the link would be
var reittiohjeet = "https://www.google.fi/maps/dir/"+pos+"/"+osoite;
And if the user rejects their location to be tracked, the link would be
var reittiohjeet2 = "https://www.google.fi/maps/dir/current+location/"+osoite;
I tried creating alternative function that would be ran in the if(navigator.geolocation)'s else clause, but that didn't seem to do anything at all.
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(60.174,24.927),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
// Luo marker
var image = 'user-location.png';
var userMarker = new google.maps.Marker({
position: pos,
map: map,
icon: image
});
map.setCenter(pos);
setMarkers(map, shops, pos);
}, function() {
handleNoGeolocation(true);
});
} else {
handleNoGeolocation(false);
}
}
function setMarkers(map, locations, pos) {
for (var i = 0; i < locations.length; i++) {
var shop = locations[i];
var myLatLng = new google.maps.LatLng(shop[1], shop[2]);
var nimi = shop[0];
var osoite = shop[5];
var puhelinnumero = shop[3];
var verkkosivu = shop[4];
var reittiohjeet = "https://www.google.fi/maps/dir/"+pos+"/"+osoite;
var content = "<div class='content'><h3>"+nimi+"</h3><strong>Osoite:</strong> "+osoite+"<br /><strong>Puhelinnumero:</strong> "+puhelinnumero+"<br /><strong>Verkkosivu:</strong> <a href='"+verkkosivu+"' target='_blank'>"+verkkosivu+"</a><br /><br /><a href='"+reittiohjeet+"'>Reittiohjeet</a></div>";
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: shop[0]
});
var infowindow = new google.maps.InfoWindow()
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
}
}
The statement in the else-clause will only be executed when the browser doesn't support geolocation.
When the user denies access the function defined as 2nd argument of getCurrentPosition will be executed.
Note: in Firefox this will not work as expected, see: Firefox 11 and GeoLocation denial callback
I am having some difficulties with getting tabbed info windows to appear for paths. I have followed this tutorial.
I have a KML layer with polylines (they curve - represent topographic features)
and do not know how to get the info window to appear when you click on a path. I've seen some tutorials on calculating midpoints (but of straight lines)..
2 ways (of many) I've tried to get path points:
var streamPoly = google.maps.Polyline.prototype.getPosition = function() {
return this.getPath().getAt(0);}
var streamPoly = poly.getPath();
What's in my header:
var map;
var streamPoly;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(42.687984,-79.394159);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'paths.kml'
});
ctaLayer.setMap(map);
ctaLayer.set('preserveViewport', true);
var infoBubble = new InfoBubble({
maxWidth: 300
});
var div = document.createElement('DIV');
div.innerHTML = 'Hello';
infoBubble.addTab('Tab 1', div);
infoBubble.addTab('Tab 2', "<B>This is tab 2</B>");
google.maps.event.addListener(streamPoly, 'click', function() {
if (!infoBubble.isOpen()) {
infoBubble.open(map, streamPoly);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
You can't access polylines in a KmlLayer as google.maps.Polyline objects. To open an InfoWindow (or an InfoBubble) on a KmlLayer, you need to add a listener to the KmlLayer:
google.maps.event.addListener(ctaLayer, 'click', function(evt) {
if (!infoBubble.isOpen()) {
infoBubble.setPosition(evt.latLng);
infoBubble.open(map);
}
});
evt will be a KmlLayerMouseEvent which will contain information about the feature clicked
Hi i am using google map to show my search locations, below the map it lists the search result. wen the user clicks the below result the google map show the infowindow .
function setMarkers(map, locations)
{
var infoWindow = new google.maps.InfoWindow({});
var markers = new Array();
var image = new google.maps.MarkerImage('images/pin_red.png',
new google.maps.Size(32,39),
new google.maps.Point(0,0),
new google.maps.Point(18, 30));
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
var alph = 65;
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var title = beach[0].split('~~');
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+String.fromCharCode(alph)+'|FF0000|000000',
shape: shape,
title: title[0]+'<br>'+title[1],
zIndex: beach[3]
});
$('#mappoint-'+String.fromCharCode(alph)).bind('click', function() {
google.maps.event.trigger(marker, 'mouseover')
});
google.maps.event.addListener(marker, 'mouseover', function() {
infoWindow.setContent(this.title);
infoWindow.open(map, this);
});
alph = parseInt(alph)+1;
}
}
This is the function i am using, it show the last created infowindow while clicking any result, anyone have any idea ?
$('#mappoint-'+String.fromCharCode(alph)).bind('click', function() {
google.maps.event.trigger(marker, 'mouseover')
});
This section having the problem, this binds only for last created marker .