set marker google maps javascript api - javascript

I am trying to create with the google maps javascript api the following: After page loading a marker should become set at the users location, what now works. After that should where the user click on the map a marker become added and the previous one deleted. One marker should be only on the map. Now the previous marker wont become deleted and other become added what I dont want. What can I do to have always one marker on the map?
var markers = [];
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 7
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map.setCenter(pos);
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event) {
deleteMarkers();
addMarkers(event.latLng);
});
addMarkers(pos);
// Adds a marker to the map and push to the array.
function addMarkers(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker);
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
marker = [];
}
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}

Take a look here I believe you are close :)
you are just setting your markers array to be nothing , but not actaully clearing the marker

Related

How do I add a user-input marker to Google Maps widget on my website, and get the latitude and longitude data from it?

How do I add a user-input marker to Google Maps widget on my website, and get the latitude and longitude data from it?
Right now I am building an application which has to allow users to drop a marker to any location so that I can get that data and process it.
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(2.8,-187.3),
mapTypeId: 'terrain'
});
// Create a <script> tag and set the USGS URL as the source.
var script = document.createElement('script');
// This example uses a local copy of the GeoJSON stored at
// http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
script.src = 'https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js';
document.getElementsByTagName('head')[0].appendChild(script);
}
// Loop through the results array and place a marker for each
// set of coordinates.
window.eqfeed_callback = function(results) {
for (var i = 0; i < results.features.length; i++) {
var coords = results.features[i].geometry.coordinates;
var latLng = new google.maps.LatLng(coords[1],coords[0]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
}
</script>
Right now I am using this, but this doesn't offer any user submitted markers.
Try running this working jsfiddle for demonstration and guidance on how users can place markers on a Google map. Note that it's based off of Google's example on adding and removing markers.
Full JS code below:
var map;
var markers = [];
function initMap() {
var haightAshbury = {
lat: 37.769,
lng: -122.446
};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: haightAshbury,
mapTypeId: 'terrain'
});
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event) {
addMarker(event.latLng);
});
// Adds a marker at the center of the map.
addMarker(haightAshbury);
}
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker);
}
You can get the marker's coordinates from the map's click event listener, e.g.:
map.addListener('click', function(event) {
console.log(event.latLng.lat());
console.log(event.latLng.lng());
addMarker(event.latLng);
});
Or from the addMarker method:
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
console.log(marker.getPosition().lat());
console.log(marker.getPosition().lng());
markers.push(marker);
}
Hope this helps!

Hide Markers on Click with Google Maps API

I am building a search form using Google Maps Javascript V3 API. I would like to add some filters that will hide certain types of markers on the map when clicked. The markers to hide are represented with
locations[i][11] == 'Other'
HTML:
Hide Other Markers
JavaScript:
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: { lat: 48.509532, lng: -122.643852}
};
var map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
var locations = <?php echo json_encode($locations_array); ?>;
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
animation: google.maps.Animation.DROP,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var content = '';
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, i));
google.maps.event.addDomListener(document.getElementsByClassName('hideOtherMarkers')[0], 'click', function() {
if (locations[i][11] == 'Other') {
marker.setVisible(false); // maps API hide call
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
When I click the link nothing fires, verified with alerts. I also tried google.maps.event.addListener (without Dom) with no success.
As commented by geocodezip this approach will not work, because i will always point behind the end of locations. Additionally this would hide at best 1 marker (the last marker that has been created).
Possible approach:
Store the visible-state of the markers in a MVCObject:
map-options:
var mapOptions = {
center: { lat: 48.509532, lng: -122.643852}
//that's the property where we store the state
visibility:new google.maps.MVCObject
};
inside the loop, after the creation of marker:
//when the state is not set yet, set it
if(typeof map.get('visibility').get(locations[i][11])==='undefined'){
map.get('visibility').set(locations[i][11],true);
}
//bind the visible-property of the marker to the state
marker.bindTo('visible',map.get('visibility'),locations[i][11]);
add the listener(outside of the loop):
google.maps.event.addDomListener(
document.getElementsByClassName('hideOtherMarkers')[0],
'click',
function() {
//simply set the desired property of the MVCObject to false
map.get('visibility').set('Other',false);
});
Demo: http://jsfiddle.net/doktormolle/5L2392mL/

How can I add new markers to Google Map in Meteor?

I'm currently adding markers on a google map when I click on a given location. The markers are currently saved both to a Collection - Markers - and in to a more classical array. What I would like to now is to add new marker to the map as they are added by other users.
My question is: Is there any way to get notified when the collection is modified (e.g. another user add a marker) ?
Maybe this is not the best way to do it. Any other suggestion?
if (Meteor.isClient) {
Template.hello.rendered = function(){
markersArray = [];
var latlng = new google.maps.LatLng(46.123, 8.843);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(latlng);
});
}
var opts = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), opts);
// add a click event handler to the map object
google.maps.event.addListener(map, "click", function(event)
{
placeMarker(event.latLng);
});
Session.set('map', true);
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
Markers.insert({"marker": location, "date": new Date()});
markersArray.push(marker);
}
}
}
As per the previous answer, you should use an observestructure, but you really need to avoid leaving the observer running forever:
Template.hello.rendered = function() {
this.markerObserve = Markers.find({}).observe({
added: function(m) {
placeMarker(m.location) // obviously depends on the structure of Markers documents
}
});
};
Template.hello.destroyed = function() {
this.markerObserve.stop();
}
You have to use observer
Template.hello.rendered = function(){
Markers.find({}).observe({
added: function (m) {
// Add marker
}
});
}

how to open popup on click of a marker from the directions service?

UPDATE
when i click green marker,it's display address of location.can i change it?
LATER EDIT :
is it possible to open popup on click of a marker from the directions service?
or try the other way like only hide a marker from the directions service(green marker) and display only red marker(hide only green marker not it's route)?is it good way?
if not possible, please suggest some alternative ideas.
OLDER:
i have a two types of marker on google map.the red marker is normal marker which represent location.and green marker is route marker(its represent many of waypoints of the map).
I modify the infowindow with textbox.which is open on click red marker.
actually i am trying to do is, first i place multiple markers on google map then i draw route between this markers.this thing is done.reminder thing is on click green marker one popup is opened in which user enter price and then click the button.then i got this value and store it to database.
the problem is:
(1) how to open same infowindow on click of green marker?
in short,how to write a code for display infowindow on click of of green marker.
how to find click event of green marker?
code is:
<script type="text/javascript">
var markerarray=new Array();
//for way points
var waypts=[];
//array in json format for placing multiple marker
var locations = <?php echo json_encode($lat1);?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
<!-- ************* for placing markers ************ -->
var marker, i;
for (i = 0; i < locations.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][3], locations[i][4]),
map: map //enable if you want marker
});
//push value into way points
waypts.push({
location:locations[i][0],
stopover:true
});
//create array for polyline
markerarray[i] = marker.getPosition();//(Array(locations[i][5], locations[i][6]));
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var data='<div style="height:150px !important"><table><tr><td>Enter Price</td></tr><tr><td><input type="text" name="prc" id="prc" /></td></tr></table></div>';
infowindow.setContent(data);
infowindow.open(map, marker);
}
})(marker, i));
}
<!-- ************** for route between markers ******************* -->
var first=locations[locations.length-1][0];
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
//directionsDisplay = new google.maps.DirectionsRenderer();
directionsDisplay = new google.maps.DirectionsRenderer({
polylineOptions: {
strokeColor: 'red',//"black",
strokeOpacity: 1.0,
strokeWeight: 3
}
});
var start = locations[0][0];//"Bopal, Ahmedabad, Gujarat, India";
var end = locations[locations.length-1][0];//"Nikol, Ahmedabad, Gujarat, India";
//remove start destination from array
waypts.shift();
//remove end destination from array
waypts.pop();
var request = {
origin:start,
destination:end,
waypoints:waypts,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
directionsDisplay.setMap(map);
</script>
Thanks in advance.
It is not impossible but it will take some time for code, The way is if you are using for mobile device then you need to accelerator from your device and call geolocation function on position change I think you understand and the second method is from purely javascript method for that you need to call your geolocation function within set Interval understand also draw line separately from marker your marker function only calls within set Intervals for getting your current location with infowindow. Example is :
var map;
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
//keep this in setInterval
// Try HTML5 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: 'Location found using HTML5.'
});
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);
}
//close here your set interval
google.maps.event.addDomListener(window, 'load', initialize);
It's possible. You can hide the default marker such that you can build a custom marker on the clicked location. This code is to hide the marker.
var rendererOptions = {
suppressMarkers : true
}
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);

Allow user to create only one Google Maps marker at a time

I have the following code that allows a user to click somewhere on the map and it records the GPS location of wherever they click. It works properly on the backend but whenever the user clicks more than once it leaves multiple markers on the map. It always keeps whatever the last location is so it works but it is somewhat confusing for the user who doesn't know what is going on on the backend. Is there some little trick I can do to make it so that whenever the user clicks to create a new marker the old one is removed?
code:
var map;
var GPSlocation;
function initialize() {
var haightAshbury = new google.maps.LatLng(37.7699298, -93.4469157);
var mapOptions = {
zoom: 4,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
}
function addMarker(location) {
//I save the location right here
GPSlocation = location;
document.getElementById("GPSlocation").value = GPSlocation;
marker = new google.maps.Marker({
position: location,
map: map
});
}
Just use setPosition method of google.maps.Marker instance:
var map,
GPSlocation,
marker; // <-- Added
// ... snip ...
function addMarker(location) {
// ... snip ...
if (!marker) {
// Create the marker if it doesn't exist
marker = new google.maps.Marker({
position: location,
map: map
});
}
// Otherwise, simply update its location on the map.
else { marker.setPosition(location); }
}
Make the marker a global variable by declaring it outside your function:
var marker;
function addMarker(location) {
GPSlocation = location;
document.getElementById("GPSlocation").value = GPSlocation;
marker = new google.maps.Marker({
position: location,
map: map
});
}
You can also make it more efficient by only updating the location of the marker rather than creating a new object:
var marker;
function addMarker(location) {
GPSlocation = location;
document.getElementById("GPSlocation").value = GPSlocation;
if (!marker) {
marker = new google.maps.Marker({
position: location,
map: map
});
} else {
marker.setPosition(location);
}
}

Categories