Cannot drag marker properly in Google Map using JavaScript - javascript

I cannot drag marker of Google Map using JavaScript. Here is my code:
geocoder.geocode( { 'address': addrs}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$('#latitude').val(results[0].geometry.location.lat());
$('#longitude').val(results[0].geometry.location.lng());
var latitude=results[0].geometry.location.lat();
var longitude=results[0].geometry.location.lng();
var title=document.getElementById('googleMap').value;
var desc=title+","+address;
console.log(latitude,longitude);
var markers = [{"lat":latitude,"lng":longitude},{"title": title,"lat":latitude,"lng":longitude,"description":desc}];
// $window.addEventListener('load', onload, false);
// $window.onload = function () {
setTimeout(function(){
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
google.maps.event.trigger(map, "resize");
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
draggable: true,
position: myLatlng,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
google.maps.event.addListener(marker, 'dragend', function (event) {
var latdrag = this.getPosition().lat();
var longdrag= this.getPosition().lng();
console.log('latlong',latdrag,longdrag);
});
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
zoomChangeBoundsListener =
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
if (this.getZoom()){
this.setZoom(12);
}
});
setTimeout(function(){google.maps.event.removeListener(zoomChangeBoundsListener)}, 2000);
},2000);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
Here my issue is I am able to drag the marker but while I am dragging the new marker is coming to droppable place and the first one is still there. Here I need that single marker will only drag to any place and no new marker will create.

You are creating two markers in the same place and dragging the top one.
var markers = [{"lat":latitude,"lng":longitude},{"title": title,"lat":latitude,"lng":longitude,"description":desc}];
creates an array with two elements and in the loop, two markers are created.

Related

Google Maps API redraw bounds on geocode

I am creating a google map that has a list of locations and then I want the user to be able to enter their(any) address into the map. Once they enter their address, a new marker must show and the bounds of the map need to update to include the new location.
I've successfully been able to set the new location as a cookie and redraw the bounds of the map on load, however when I try and do this on the geocode input click, the new marker loads, but the bounds seem to only redraw around the new location.
How can I get the bounds to redraw on the input?
Dev site link: http://rosemontdev.com/google-maps-api/
Here is my code:
var locations = [
['Dripping Springs', 30.194826, -97.99839],
['Steiner Ranch', 30.381754, -97.884735],
['Central Austin', 30.30497, -97.744086],
['Pflugerville', 30.450049, -97.639163],
['North Austin', 30.41637, -97.704623],
];
var currentLocationMarker = "http://rosemontdev.com/google-maps-api/wp-content/themes/rm-theme/images/current.png";
var locationMarker = "http://rosemontdev.com/google-maps-api/wp-content/themes/rm-theme/images/pin.png";
function initMap() {
window.map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
var geocoder = new google.maps.Geocoder();
document.getElementById('submit').addEventListener('click', function() {
geocodeAddress(geocoder, map);
});
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locationMarker,
});
var circle = new google.maps.Circle({
map: map,
radius: 3000,
fillColor: '#2B98B0',
fillOpacity: 0.2,
strokeOpacity: 0.25,
});
circle.bindTo('center', marker, 'position');
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infoWindow.setContent(locations[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
} //closing for locations loop
var locationValue = Cookies.get('rmLocationCookie-Place');
var longValue = Cookies.get('rmLocationCookie-Long');
var latValue = Cookies.get('rmLocationCookie-Lat');
currentLocationNewMarker = new google.maps.Marker({
position: new google.maps.LatLng(longValue, latValue),
map: map,
icon: currentLocationMarker,
});
bounds.extend(currentLocationNewMarker.position);
map.fitBounds(bounds);
} //closing initMap
function geocodeAddress(geocoder, resultsMap) {
var address = document.getElementById('address').value;
var infoWindow = new google.maps.InfoWindow();
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
var currentLocationData = [];
var bounds = new google.maps.LatLngBounds();
var currentLocationName = 'Current Location';
var currentLocationLong = results[0]['geometry']['bounds']['f']['b'];
var currentLocationLat = results[0]['geometry']['bounds']['b']['b'];
currentLocationData.push(currentLocationName, currentLocationLong, currentLocationLat);
//Location Value Entered
Cookies.set('rmLocationCookie-Place', address);
//Geocoded Long
Cookies.set('rmLocationCookie-Long', currentLocationLong);
//Geocoded Lat
Cookies.set('rmLocationCookie-Lat', currentLocationLat);
var locationValue = Cookies.get('rmLocationCookie-Place');
if(locationValue === undefined){
console.log('no cookie set');
$('#cookie-notice').html('Your location is not saved.');
}
else{
$('#cookie-notice').html('Your location is saved as ' + locationValue +'');
}
updatedCurrentLocationMarker = new google.maps.Marker({
position: new google.maps.LatLng(currentLocationLong, currentLocationLat),
map: map,
icon: currentLocationMarker,
});
bounds.extend(updatedCurrentLocationMarker.position);
map.fitBounds(bounds);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
Try this:
Keep track of the original bounds before each geocode.
Then once the geocode completes pan to the marker and get the new map bounds the.
The idea is then to union the old and new bounds together using the. Union method then use the result as tour new map boundary.
originalbounds.union(newbounds)

Google Maps API: Multiple GeoJson layers with MarkerClusterer + toggle

I have a problem with my GeoJson layers which I want to cluster (with MarkerClusterer) and then be able to show and hide them via checkboxes or similar. Therefore I tried something like the code below:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.515696, 13.392624),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
var bounds = new google.maps.LatLngBounds();
var barLayer = new google.maps.Data();
var cafeLayer = new google.maps.Data();
barLayer.loadGeoJson('json/eat_drink/bar.geojson');
cafeLayer.loadGeoJson('json/eat_drink/cafe.geojson');
var markerClusterer = new MarkerClusterer(map);
var infowindow = new google.maps.InfoWindow();
markerClusterer.setMap(map);
function displayMarkers(layer) {
var layer = layer;
google.maps.event.addListener(layer, 'addfeature', function (e) {
if (e.feature.getGeometry().getType() === 'Point') {
var marker = new google.maps.Marker({
position: e.feature.getGeometry().get(),
title: e.feature.getProperty('name'),
map: map
});
// open the infoWindow when the marker is clicked
google.maps.event.addListener(marker, 'click', function (marker, e) {
return function () {
var myHTML = e.feature.getProperty('name');
infowindow.setContent("<div style='width:150px; text-align: center;'>"+myHTML+"</div>");
infowindow.setPosition(e.feature.getGeometry().get());
infowindow.setOptions({pixelOffset: new google.maps.Size(0,-30)});
infowindow.open(map, marker);
};
}(marker, e));
markerClusterer.addMarker(marker);
bounds.extend(e.feature.getGeometry().get());
map.fitBounds(bounds);
map.setCenter(e.feature.getGeometry().get());
}
});
layer.setMap(null);
google.maps.event.addListener(map, "click", function () {
infowindow.close();
});
};
document.getElementById('bar').onclick = function(){ // enable and disable markers
if(document.getElementById('bar').checked == true){
displayMarkers(barLayer);
}else{
return null;
}
};
}
Unfortunatley this doesn't work and I don't no exactly why.
If I remove the displayMarkers() function around the code and replace "layer" with the desired GeoJson layer, e.g. "barLayer", it works just fine.
Since I will end up with tons of GeoJason layers I would prefer a "compact" solution like this insted of copying the code multiple times. Have you guys any ideas how to do that properly?
I'm afraid I haven't done much more than refactor your code. Could you give this a try, and if it doesn't work specify exactly what doesn't work?
function displayMarkers(layer, map, markerClusterer) {
google.maps.event.addListener(layer, 'addfeature', function(e) {
if (e.feature.getGeometry().getType() === 'Point') {
var marker = new google.maps.Marker({
position: e.feature.getGeometry().get(),
title: e.feature.getProperty('name'),
map: map
});
// open the infoBox when the marker is clicked
google.maps.event.addListener(marker, 'click', function(e) {
var myHTML = e.feature.getProperty('name');
var infowindow = new google.maps.InfoWindow();
infowindow.setContent("<div style='width:150px; text-align: center;'>" + myHTML + "</div>");
infowindow.setPosition(e.feature.getGeometry().get());
infowindow.setOptions({
pixelOffset: new google.maps.Size(0, -30)
});
infowindow.open(map, marker);
google.maps.event.addListener(map, "click", function() {
infowindow.close();
});
});
markerClusterer.addMarker(marker);
var bounds = new google.maps.LatLngBounds();
bounds.extend(e.feature.getGeometry().get());
map.fitBounds(bounds);
map.setCenter(e.feature.getGeometry().get());
}
});
layer.setMap(null);
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.515696, 13.392624),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var barLayer = new google.maps.Data();
var cafeLayer = new google.maps.Data();
barLayer.loadGeoJson('json/eat_drink/bar.geojson');
cafeLayer.loadGeoJson('json/eat_drink/cafe.geojson');
var markerClusterer = new MarkerClusterer(map);
markerClusterer.setMap(map);
document.getElementById('bar').onclick = function() { // enable and disable streetViewControl
if (document.getElementById('bar').checked == true) {
displayMarkers(barlayer, map, markerClusterer);
} else {
return null;
}
};
}

how to hide google map markers by a button?

I have a Google map. I created some markers, but I can not hide these markers. I looked at this document. I have one function, but it failed.
function LoadMap () {
var markers = JSON.parse('<%=Stations() %>');
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
map2 = new google.maps.Map(document.getElementById("map_canvas2"), mapOptions2);
for (i = 0; i < markers.length; i++) {
var data = markers[i]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map2,
title:"Hello",
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
icon: InitIcon
});
}(marker, data);
}
}
You need to apply the setMap(null) to your Array of markers.
If your markers variable contains all your markers, you need to loop through each markers and delete each of them using
markers[i].setMap(null);
as shown on your sample
BTW, your code contains somme errors, like a missing ; after var data = markers[i]

Google Maps - center map on marker click

I have the following code for placing several markers on a google map.
What I now want to do is when the user clicks on a marker it zooms in and then centers the map to the marker position (this is the bit that's not working - towards the end of the code in the setMarkers function).
Any ideas?
var infowindow = null;
var sites = [];
var partsOfStr = [];
var partsOfStr2 = [];
var bounds;
$(document).ready(function () {
$("select[id*='coordList']").find("option").each(function () {
partsOfStr = $(this).val().split(',');
partsOfStr2 = $(this).text().split('^');
sites.push([partsOfStr2[0], parseFloat(partsOfStr[0]), parseFloat(partsOfStr[1]), partsOfStr[2], partsOfStr2[1], partsOfStr2[2], partsOfStr2[3], partsOfStr[3], partsOfStr[4], partsOfStr[5]]);
});
initialize();
});
function initialize() {
bounds = new google.maps.LatLngBounds();
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng(54.57951, -4.41387),
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
setMarkers(map, sites);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
google.maps.event.addListener(infowindow,'closeclick',function(){
map.setCenter(new google.maps.LatLng(54.57951, -4.41387));
map.setZoom(6);
});
}
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: sites[0],
html: "<div class='mapDesc'>content here...</div>"
});
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
map.setCenter(marker.getPosition()); // NOT WORKING!!!!!!!
map.setZoom(10);
});
bounds.extend(new google.maps.LatLng(sites[1], sites[2]));
map.fitBounds(bounds);
}
}
marker is left pointing to the last marker added. Either use function closure or "this" like you did for the infowindow:
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
map.setCenter(this.getPosition());
map.setZoom(10);
});
google.maps.event.addListener(marker, "click", function (evt) {
infowindow.setContent(this.html);
infowindow.open(map, this);
map.setCenter(evt.latLng);
map.setZoom(10);
});
that will working in my own app

Google maps zoom level for country

I'm having a problem working out how to set the zoom level for different countries, I have managed to get the map working and displaying the country, just cannot seem to work out how to set the zoom level.
Any help would be appreciated.
Thanks
George
<script type="text/javascript">
var infowindow = null;
$(document).ready(function () { initialize(); });
function initialize() {
//var geocoder = new google.maps.Geocoder();
//geocoder.geocode({ 'address': address }, function (results, status) {
// if (status == google.maps.GeocoderStatus.OK) {
// map.setCenter(results[0].geometry.location);
// map.fitBounds(results[0].geometry.viewport);
// }
//});
var centerMap = new google.maps.LatLng(#Html.Raw(#item.strLatLong));
var myOptions = {
zoom: 4, //<<-------How can I chnage this
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("WeatherMapLocation"), myOptions);
setMarkers(map, sites);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map);
}
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
title: sites[0],
zIndex: sites[3],
html: sites[4]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
}
</script>
From the documentation on the Geocoder, there is a viewport and a bounds returned in the geocoder's response which can be used to center and zoom the map on the result.
if (results && results[0] && results[0].geometry && results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
working example

Categories

Resources