I am writing this question, having previously searched quite a lot for this question, but haven't found a thread that I can use for my current problem. (Probably due to lack of skill). If there is a question that addresses exactly this, please redirect me to it!
I am creating a PWA that uses google maps for user interaction, the idea being that a user can place a marker on said map by either:
- Clicking the map on the desired location
- Clicking a button that places a marker on the user's current location
- Writing the address (geocoding)
For now, I have a code that permits me doing the first two actions. In both functions, I have an IF, that tries to overwrite any existing markers, so as to only have a maximum of one marker on the map. (Ignore geocoding remark, it hasn't been implemented yet)
I come across the following problem: Whilst if the user clicks the map, and then clicks the geolocating button, the first marker is removed. (Desired outcome)
- If the user clicks the geolocating button, and then clicks the map, no marker is removed. Screenshot of outcome:
I can't get a working HTML/CSS/Javascript snippet to work, as it requires hiding the google maps key, and that exceeds my capabilities. But I think that the problem(s) lie in my Javascript code:
var map2;
var marker2;
function initialize2() {
google.maps.controlStyle = 'azteca';
var mapOptions2 = {
zoom: 15,
minZoom: 12,
maxZoom:19,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: false,
fullscreenControl: false,
gestureHandling: "greedy",
center: new google.maps.LatLng(41.727751, 1.827424),
restriction: {
latLngBounds: {
north: 41.753,
south: 41.715,
east: 1.857,
west: 1.806,
},
},
styles: [{ // VISIBLE BARS RESTAURANTS
featureType: "poi",
stylers: [{ visibility: "off" }],
}, {
featureType: "poi.park",
stylers: [{ visibility: "on" }],
}, {
featureType: "poi.park",
elementType: "labels",
stylers: [{ visibility: "off" }],
}, {
featureType: "transit",
stylers: [{ visibility: "off" }],
}]
};
map2 = new google.maps.Map(document.getElementById('map-canvas-inseg'), mapOptions2);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(onSuccessGeolocating);
}
// Add marker when map is clicked (and overwrite when it is clicked again)
google.maps.event.addListener(map2, 'click', function(event) {
placeMarker(event.latLng);
});
function placeMarker(location) {
if (marker2 == null)
{
marker2 = new google.maps.Marker({
position: location,
map: map2
});
}
else
{
marker2.setPosition(location);
}
}
function onSuccessGeolocating(position) {
var circleBigOpt = {
center: new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
map: map2,
radius: position.coords.accuracy,
fillColor:"#4285f4",
fillOpacity:0.1,
strokeWeight:0
};
var circleBig = new google.maps.Circle(circleBigOpt);
var positionMarkerOptions = {
position: new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10,
fillColor: '#4285f4',
fillOpacity: 1,
strokeColor: '#ffffff',
strokeWeight: 1
},
map: map2
};
var marker = new google.maps.Marker(positionMarkerOptions);
map2.setCenter(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
// Function that adds marker on the user's current location, when button "boto-marcarMapa" is clicked
document.getElementById("boto-marcarMapa").addEventListener("click", function( event ) {
if (marker2 == null)
{
marker2 = new google.maps.Marker({
position: new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
map: map2
});
}
else
{
//marker2.setPosition(position);
marker2 = new google.maps.Marker({
position: new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
map: map2
});
}
//marker2.setMap(null);
});
}
}
window.addEventListener('load', initialize2);
Clarification: marker2 is the interactive marker that users create through the 3 actions stated. marker is just a blue dot that appears automatically on user's current location if the function onSuccessGeolocating gets approved.
I know there are a lot of google.maps.Marker related questions, and I have really tried resolving this on my own (setting marker2 as global variable, trying to set map's markers to null before the functions..) but have gotten nowhere.
Thank you very much, and sorry for possibly confusing code lines.
CodePudding user response:
The issue is that you create new markers, but you don't reference back to it in placeMarker
when you want to replace the position later on.
var map2;
var marker2;
function initialize2() {
google.maps.controlStyle = 'azteca';
var mapOptions2 = {
zoom: 15,
minZoom: 12,
maxZoom:19,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: false,
fullscreenControl: false,
gestureHandling: "greedy",
center: new google.maps.LatLng(41.727751, 1.827424),
restriction: {
latLngBounds: {
north: 41.753,
south: 41.715,
east: 1.857,
west: 1.806,
},
},
styles: [{ // VISIBLE BARS RESTAURANTS
featureType: "poi",
stylers: [{ visibility: "off" }],
}, {
featureType: "poi.park",
stylers: [{ visibility: "on" }],
}, {
featureType: "poi.park",
elementType: "labels",
stylers: [{ visibility: "off" }],
}, {
featureType: "transit",
stylers: [{ visibility: "off" }],
}]
};
map2 = new google.maps.Map(document.getElementById('map-canvas-inseg'), mapOptions2);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(onSuccessGeolocating);
}
// Add marker when map is clicked (and overwrite when it is clicked again)
google.maps.event.addListener(map2, 'click', function(event) {
placeMarker(event.latLng);
});
function placeMarker(location) {
if (marker2 == null)
{
marker2 = new google.maps.Marker({
position: location,
map: map2
});
}
else
{
marker2.setPosition(location);
}
}
function onSuccessGeolocating(position) {
var circleBigOpt = {
center: new google.maps.LatLng(position.coords.latitude,position.coords.longitude),
map: map2,
radius: position.coords.accuracy,
fillColor:"#4285f4",
fillOpacity:0.1,
strokeWeight:0
};
var circleBig = new google.maps.Circle(circleBigOpt);
new google.maps.Marker({
position: location,
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 10,
fillColor: '#4285f4',
fillOpacity: 1,
strokeColor: '#ffffff',
strokeWeight: 1
},
map: map2
});
map2.setCenter(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
// Function that adds marker on the user's current location, when button "boto-marcarMapa" is clicked
document.getElementById("boto-marcarMapa").addEventListener("click", function( event ) {
placeMarker(new google.maps.LatLng(position.coords.latitude,position.coords.longitude));
//marker2.setMap(null);
});
}
}
window.addEventListener('load', initialize2);
Side-note: in the URL in your <script>
tag, you should have a callback
search parameter (usually callback=oninit
), Google's script will call this through window.oninit
when it's been loaded, so I'd replace your window event listener with:
window.oninit = initialize2;
CodePudding user response:
The issue is that you create a new variable (marker) that holds the newly created marker, but you don't reference back to it in placeMarker when you want to replace the position later on.
I've changed your placeMarker function to take a type argument which is null or "circle" to be able to change the marker2 instance options without redundant code. There's a lot of code that needs improvement but this will achieve your desired outcome.