removing last added marker from google maps v3 - javascript

I'm working on a site that uses google maps v3, thanks to which you can navigate to a specific location
web site - http://dev.fama.net.pl/walendia/lokalizacja.html
type 'szczecin' on input that is at the top of the site and click submit - a marker will appear on the map, then type 'warszawa' - new marker will appear on the map but old one is still there, how to remove previous marker from the map
GOOGLE MAP CODE
var map;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var geocoder = new google.maps.Geocoder();
var stepDisplay;
var markersArray = [];
var iconSize = new google.maps.Size(158,59);
var iconOrigin = new google.maps.Point(0,0);
var iconAnchor = new google.maps.Point(20,59);
function initialize(center, zoom) {
directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});
var mapOptions = {
zoom: zoom,
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.TOP_RIGHT
}
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
geocoder.geocode({address: center}, function(results, status) {
map.setCenter(results[0].geometry.location);
});
}
function addMarker(location, icon) {
geocoder.geocode({address: location}, function(results, status) {
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
icon: icon
});
google.maps.event.addListener(marker);
markersArray.push(marker);
});
}
function addMarker2(position, icon) {
var location = new google.maps.LatLng(52.08901624831595, 20.854395031929016);
var icon = {
url: 'http://dev.fama.net.pl/walendia/img/markers/end.png',
size: iconSize,
origin: iconOrigin,
anchor: iconAnchor
}
marker = new google.maps.Marker({
position: location,
map: map,
icon: icon
});
markersArray.push(marker);
}
function calcRoute(start, end) {
var start = start;
var end = end;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
var location = start;
var icon = {
url: 'http://dev.fama.net.pl/walendia/img/markers/start.png',
size: iconSize,
origin: iconOrigin,
anchor: iconAnchor
}
addMarker(location, icon);
addMarker2(location, icon);
directionsDisplay.setDirections(result);
}
});
}
// SET CENTER ON RESIZE
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
directionsDisplay.setMap(map);
});
$(document).ready(function() {
$('.form-box form').submit(function() {
var start = $(this).find('input[name="start"]').val();
var end = new google.maps.LatLng(52.08901624831595, 20.854395031929016);
directionsDisplay.setMap(map);
calcRoute(start, end);
return false;
});
});
HTML CODE
$(document).ready(function() {
initialize('Łączności 131, 05-552 Łazy, Polska', 10);
addMarker2(location);
});

Before adding second marker you need to delete marker from markersArray. Use the following function to delete markers from array.
function deleteMarkers() {
if (markersArray) {
for (i=0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
DEMO FIDDLE
NOTE: I just took some sample to remove and show markers when you click on buttons. Use those functions according to your requirement.

Related

Marker new postion created but old is also showing in ajax google map

Hi i'm trying to get markers latlon from ajax, i m getting ajax data every second and also able to create marker within radius , now i'm facing problem with updating marker positions as in current new marker created and old one also showing. Pls help to update markers which i am getting from ajax and remove extra.
var map = null;
var geocoder = null;
var markers = {};
var infoWindow = null;
var minZoomLevel = 16;
jQuery('#search').click(function() {
var address = jQuery('#address').val() || 'India';
if (map === null)
initializeMap();
searchAddress(address);
});
function initializeMap() {
var mapOptions = {
zoom: minZoomLevel,
draggable: true,
disableDefaultUI: true,
scrollwheel: true,
disableDoubleClickZoom: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
});
}
google.maps.event.addListener(map, "idle", function(event) {
searchStoresBounds();
});
geocoder = new google.maps.Geocoder();
infoWindow = new google.maps.InfoWindow();
}
function searchAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var latlng = results[0].geometry.location;
map.setCenter(latlng);
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
searchStoresBounds();
} else {
alert('Geocode was failed: ' + status);
}
});
}
setInterval(function searchStoresBounds() {
var bounds = map.getCenter().toUrlValue();
var url = './store.php';
var parameter = { bounds: bounds };
jQuery.ajax({
url: url,
data: parameter,
dataType: 'json',
success: showStores
});
}, 1000);
function showStores(data, status, xhr) {
if (data['status'] != 'OK')
return;
var id;
// add markers for new stores
for (id in data['data']) {
if (markers[id] === undefined)
createMarker(id, data['data'][id]);
}
var b = map.getBounds();
// remove markers out of the bounds
for (id in markers) {
if (! b.contains(markers[id].getPosition())) {
markers[id].setMap(null);
delete markers[id];
}else{createMarker(id, data['data'][id]);}
}
}
function createMarker(id, store) {
var latlng = new google.maps.LatLng(
parseFloat(store['lat']),
parseFloat(store['lng'])
);
var html = "<b>" + store['address'] + "</b>";
var x = store['distance'];
var y = 1000;
var z = x * y;
var m = 85;
var t = z / m;
document.getElementById("demo").innerHTML = Math.ceil(t);
var headm = store['bearing'];
var car = "M17.402,0H5.643C2.526,0,0,3.467,0,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759c3.116,0,5.644-
2.527,5.644-5.644 V6.584C23.044,3.467,20.518,0,17.402,0z M22.057,14.188v11.665l-2.729,0.351v-4.806L22.057,14.188z
M20.625,10.773 c-1.016,3.9-2.219,8.51-2.219,8.51H4.638l-2.222-8.51C2.417,10.773,11.3,7.755,20.625,10.773z
M3.748,21.713v4.492l-2.73-0.349 V14.502L3.748,21.713z M1.018,37.938V27.579l2.73,0.343v8.196L1.018,37.938z
M2.575,40.882l2.218-3.336h13.771l2.219,3.336H2.575z M19.328,35.805v-7.872l2.729-0.355v10.048L19.328,35.805z";
var icon = {
path: car,
scale: .7,
strokeColor: 'White',
strokeWeight: .4,
fillOpacity: 1,
fillColor: '#333333',
offset: '5%',
rotation: parseInt(headm),
// rotation: parseInt(heading[i]),
anchor: new google.maps.Point(10, 25) // orig 10,50 back of car, 10,0 front of car, 10,25 center of car
};
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
markers[id] = marker;
}
You are facing the issue due to this part
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
Everytime you get data from ajax it creates a new marker.
Add the following declaration at the top of your js page
var marker;
and change the marker creation to the following
if(marker)
{
marker.setMap(null);
}
marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
Before you create a new marker the previous one is removed from the map. The if(marker) part is needed to check if a marker instance has been created because the first time that you run there will be no marker and you will get an error while trying to remove the marker.
Edit 1 :
As you have multiple markers you will need to store an array of markers and remove them before adding new markers on map
At the top of the page you will need to declare
var markerArray = new Array();
Just before you add the markers you will need to clear the previous markers
for(var i = 0; i<markerArray.length; i++)
{
markerArray[i].setMap(null);
}
markerArray = new Array()
After that will be your current code
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: icon,
});
markerArray.push(marker);
You will need to add the marker to the markerArray so that it can be cleared the next time your code executes.

Google map Remove previous route and draw a new route

Currently I have encounter a problem. I used and changed sample API to draw route for two points. Point A is current location. Point B is one of the multiple markers' location. Those markers are created which I call nearby search function.
function showInfoWindow() {
var marker = this;
places.getDetails({
placeId: marker.placeResult.place_id
},
function(place, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
infoWindow.open(map, marker);
buildIWContent(place);
});
var clickLat = marker.position.lat();
var clickLon = marker.position.lng();
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
var directionsService = new google.maps.DirectionsService();
showRoute(clickLat, clickLon, directionsDisplay, directionsService);
}
function showRoute(clickLat, clickLon, directionsDisplay, directionsService) {
var pointA = {
lat: currentLat,
lng: currentLon
};
var pointB = {
lat: clickLat,
lng: clickLon
};
directionsDisplay.setOptions({
suppressMarkers: true
});
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
// Set destination, origin and travel mode.
var request = {
destination: pointB,
origin: pointA,
travelMode: google.maps.TravelMode.DRIVING
};
//directionsDisplay.setMap(null);
// Pass the directions request to the directions service.
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the route on the map.
//directionsDisplay.set('directions', null);
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
These codes could draw route for two points already. But the problem is when I click one marker call the showInfoWindow() it will draw one route, and click another one when it will call the showInfoWindow() again it will draw another route remaining the previous one route.I want to clear the previous one route. Tried all the methods online and could not find the reason.
If you only want one directions result displayed on the map at the time, only create and use one instance of the DirectionsRenderer, currently you create a new one for every result from the DirectionsService.
proof of concept fiddle
code snippet:
var geocoder;
var map;
var places;
var infoWindow = new google.maps.InfoWindow();
//Jersey City, NJ, USA
var currentLat = 40.7281575;
var currentLon = -74.0776417;
// global reference to the DirectionsRenderer
var directionsDisplay;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
places = new google.maps.places.PlacesService(map);
// initialize the global DirectionsRenderer
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
var marker1 = new google.maps.Marker({ /* New York, NY, USA */
position: {
lat: 40.7127837,
lng: -74.0059413
},
placeResult: {
place_id: "ChIJOwg_06VPwokRYv534QaPC8g"
},
map: map
});
google.maps.event.addListener(marker1, 'click', showInfoWindow);
var marker2 = new google.maps.Marker({ /* Newark, NJ, USA */
position: {
lat: 40.735657,
lng: -74.1723667
},
placeResult: {
place_id: "ChIJHQ6aMnBTwokRc-T-3CrcvOE"
},
map: map
});
google.maps.event.addListener(marker2, 'click', showInfoWindow);
var bounds = new google.maps.LatLngBounds();
bounds.extend(marker1.getPosition());
bounds.extend(marker2.getPosition());
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
function showInfoWindow() {
var marker = this;
places.getDetails({
placeId: marker.placeResult.place_id
},
function(place, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
return;
}
infoWindow.open(map, marker);
buildIWContent(place);
});
var clickLat = marker.position.lat();
var clickLon = marker.position.lng();
var directionsService = new google.maps.DirectionsService();
showRoute(clickLat, clickLon, directionsDisplay, directionsService);
}
function showRoute(clickLat, clickLon, directionsDisplay, directionsService) {
var pointA = {
lat: currentLat,
lng: currentLon
};
var pointB = {
lat: clickLat,
lng: clickLon
};
directionsDisplay.setOptions({
suppressMarkers: true
});
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
// Set destination, origin and travel mode.
var request = {
destination: pointB,
origin: pointA,
travelMode: google.maps.TravelMode.DRIVING
};
//directionsDisplay.setMap(null);
// Pass the directions request to the directions service.
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the route on the map.
//directionsDisplay.set('directions', null);
//directionsDisplay.setMap(map);
//directionsDisplay.setDirections({ routes: [] });
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
html,
body,
#map_canvas {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>

Cordova Device Ready Initialize Google Map

I have this Javascript code on Google maps with geolocation and direction and I am using it in cordova , it gives me problems because it lacks the event Deviceready.
I tried to put it , but it was not working.
You are able to add it in the right way ?
Code:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
// default location. When geolocation tracks the client, this variable is set to that location
function initialize() {
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//here there is marker
directionsDisplay.setMap(map);
map.setCenter(mylocation);
}
function updateRoute() {
calcRoute(mylocation);
}
function calcRoute(start) {
var start = mylocation;
var end = document.getElementById('end').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.WALKING,
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
mylocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
//document.getElementById('start').value = ;
if (map) {
calcRoute(position.coords.latitude +','+ position.coords.longitude);
map.setCenter(mylocation);
//*Posizione Utente*//
var image = 'user.png'
var marker1 = new google.maps.Marker({
position: mylocation,
map: map,
title: 'ciao!',
icon: image
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow1.open(map,marker1);
});
var infowindow1 = new google.maps.InfoWindow({
content: '<img src="user.png">Sono Qui.....'
});
}
})
}
google.maps.event.addDomListener(window, 'load', initialize);

How to use an existing marker for Google Maps API directionService instead of defining a new one?

I'm using Google Maps API to show directions to a location.
On page load, I set a marker on the map: (FYI: I haven't included the coordinates, but you can assume they are defined)
var destination = [xxx, yyy, 11, xxx, yyy]; //x-coord,y-coord,zoom,x-center,x-center
var dublin = [xxx, yyy, 11, xxx, yyy]; //x-coord,y-coord,zoom,x-center,x-center
var directionsService = new google.maps.DirectionsService();
var directionsDublin;
function initialize() {
directionsDublin = new google.maps.DirectionsRenderer();
var centerMap = new google.maps.LatLng(destination[3],destination[4]);
map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: centerMap,
zoom: destination[2]
});
marker1 = new google.maps.Marker({
position: new google.maps.LatLng(destination[0], destination[1]),
map: map
});
marker1.setAnimation(google.maps.Animation.DROP);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
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.event.addDomListener(window, 'load', initialize);
So the code above displays the map with a marker on it.
I now have a button #tNorth. Clicking it will show a route from a defined location. Clicking again will remove the route and return to the original view.
$(document).ready(function() {
$( "#tNorth" ).on( "click", function() {
if ($("#north").css('display') != 'none') {
//set zoom and center
map.setZoom(destination[2]);
map.setCenter(new google.maps.LatLng(destination[3], destination[4]));
//remove the route
directionsDublin.setMap(null);
//remove the text
$("#north").css('display':'none');
}
else {
//create travel route
var request2 = {
origin: new google.maps.LatLng(dublin[0], dublin[1]),
destination: new google.maps.LatLng(destination[0], destination[1]),
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
//display route on map
directionsDublin.setMap(map);
directionsService.route(request2, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDublin.setDirections(result);
}
});
//add the text
$("#north").css('display':'block');
}
});
});
This is my first use of the Maps API so I'm pretty happy!!
However, when the route is displayed, it places 2 new markers on the page. Since the destination marker is already on the page, it gets overlayed by the new marker.
Is there a way for me to, instead of defining destination: new google.maps.LatLng(destination[0], destination[1]), that I could instead define something like destination: marker1??
It would be nicer than displaying two markers over each other...
Use {suppressMarkers:true} in the DirectionRendererOptions to prevent the DirectionsRenderer from adding markers to the map (it will still show the route)
directionsDublin = new google.maps.DirectionsRenderer({suppressMarkers:true});

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