Google maps placemark doesn't replace old placemark - javascript

I'm developing a web page with a Google Maps application and there is something that I'm having trouble with. As it stands, the web page has a functional map (without any layers) and a search bar. I'm new to programming so hopefully there is a quick fix that I'm missing.
When I look up an address, the placemark is is positioned where it is supposed to be. However, when I make a second search with a different address, the placemark of the first search remains visible so that there are two placemarks on the screen. How can I make a new placemark replace the old one?
<script type="text/javascript">
var geocoder;
var map;
var marker;
function initialize() {
geocoder = new google.maps.Geocoder ();
var latlng = new google.maps.LatLng (55.1667, -114.4000);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
marker = new google.maps.Marker({map:map});
}
function codeAddress () {
var address = document.getElementById ("address").value;
geocoder.geocode ( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results [0].geometry.location);
marker.setposition(results [0].geometry.location);
map.setZoom(16);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>

One way to achieve what you describe is with a global marker variable. Since the codeAddress function is calling new google.maps.Marker every time it runs, you will get a new marker each time.
Instead, use the setPosition function of the global marker to move it around.
var geocoder;
var map;
// ADDED
var marker;
function initialize() {
geocoder = new google.maps.Geocoder ();
var latlng = new google.maps.LatLng (55.1667, -114.4000);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
// ADDED
marker = new google.maps.Marker({ map: map });
}
function codeAddress () {
var address = document.getElementById ("address").value;
geocoder.geocode ( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results [0].geometry.location);
// CHANGED
marker.setPosition(results [0].geometry.location);
map.setZoom(16);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}

Related

Set center for google map by using yii2-google-maps-markers

I'm using yii2-google-maps-markers for my webste.
It works fine.
I want to create a search engine, so I want to change the center value of google map after searched result shown.
I could change the center position but all makers removed.
How I can change center by using js with a specified address without removing makers.
My code is below:
view.php
<?php
echo GoogleMaps::widget([
'userLocations' => $locat,
'googleMapsUrlOptions' => [
'key' => Yii::$app->params['GOOGLE_API_KEY'],
],
'googleMapsOptions' => [
],
'wrapperHeight' => '350px',
]);
?>
and current solution
<script type="text/javascript">
// Run function after page loaded
document.addEventListener('DOMContentLoaded', function() {
show_map_theo_address("some where, America");
}, false);
// This is the minimum zoom level that we'll allow
function show_map_theo_address(address) {
var geocoder, vitri;
var minZoomLevel = 15;
geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
vitri = results[0].geometry.location;
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
}
}
});
}
}
But it does not work.
Please help.
You should separate the logic .. a first part for show the map and all the markers a second part for get the new marker position and set the center
This beacuse you create (recreate) the maps when you use the actual show_map_theo_address function
for avoid the markers deletion you should
create a global var map
<script>
var map;
......
move the creation of the map outside the function show_map_theo_address()
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(YourInitialCenterLat, YourInitialCenterLng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
inside the function show_map_theo_address() use setCenter
// This is the minimum zoom level that we'll allow
function show_map_theo_address(address) {
var geocoder, vitri;
var minZoomLevel = 15;
geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
vitri = results[0].geometry.location;
map.setCenter(new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng()));
}
}
}
});
}
}

geocode a marker in Google Maps

I was roaming on this site for any info on geocoding a marker. However, I have tried some of the answers but I did not manage to make it work (I am an amateur when it comes to coding), so could someone please help me with the geocoding of my marker? Apparantly, the marker is missing when using this code. I need to geocode postcode in this case, which is the zip code 1058JA. Thanks in advance!
var geocoder;
var map;
var Postcode;
Postcode = '1058JA';
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(52.368465, 4.903921);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
function codeAddress() {
geocoder = new google.maps.Geocoder();
geocoder.geocode( {'address': document.getElementById("address").value },
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
Postcode = results[0].geometry.location;
map = new google.maps.Map(document.getElementById("map_canvas"),
{
center: Postcode,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker=new google.maps.Marker({
position:results[0].geometry.location,
});
marker.setMap(map);
}
else {
document.getElementById("address").value = status;
}
}
);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
There are a few things wrong with your code.
1) codeAddress is never called (as Anto Jurković notes).
2) A new instance of map is created within codeAddress if it were ever called which is redundant.
3) While you've specified Postcode as a string at the top of the code, the geocoder is looking for the value of a input element instead.
Your code should something like this:
var geocoder;
var map;
var Postcode;
Postcode = '1058JA';
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(52.368465, 4.903921);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress();
}
function codeAddress() {
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': Postcode }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
});
marker.setMap(map);
} else {
document.getElementById("address").value = status;
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Demo

Google Maps Apiv3 - Geocode function to get latitude longtitude not working

I modified the javascript from https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-simple to
var geocoder;
var postalArr = [];
postalArr.push(249586);
postalArr.push(266751);
var map;
function initialize(){
var myLatlng = new google.maps.LatLng(1.3667, 103.7500);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
if (postalArr) {
for (var i = 0; i < postalArr.length; i++ ) {
codeAddress(postalArr[i]);
}
}
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
}
function codeAddress(postal) {
geocoder.geocode( { 'postal': postal}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var markerE = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
The script goes within the for loop but doesn't run the codeAddress function.
I'm not sure why.
Two things.
(1) need to define geocoder somewhere, I put it in the initialize
function initialize(){
geocoder = new google.maps.Geocoder();
(2) there's no such thing as a postal property to feed the geocoder. Valid requests are for a latlng or an address as explained here.
So at least you must specify a country. I'm not sure what country 249586 is for, in my demo I used two California zip codes, and added ", United States" to the address.
geocoder.geocode( { 'address': postal + ", United States"},

Google Maps PanTo OnClick

I am trying to panTo an area on a map on click. The script is not working and page reloading. Perhaps someone can see the problem.
My function
function clickroute(lati,long) {
map = google.maps.Map(document.getElementById("map_canvas"));
map.panTo(lati,long)
}
And the rest
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
directionsDisplay = new google.maps.DirectionsRenderer();
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var myOptions = {
zoom:10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: chicago
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var address = 'virginia water';
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
});
directionsDisplay.setMap(map);
}
function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
And my event
test
The issue is that your using map.panTo(latitude,longitude) but the google maps API uses this: panTo(latLng myLatLng) where latLng is a google map class.
try something like this (untested)
function clickroute(lati,long) {
var latLng = new google.maps.LatLng(lati, long); //Makes a latlng
map.panTo(latLng); //Make map global
}
Look here for more info.
EDIT
As someone else stated you don't want to remake a new map. Maybe its easier to make it global?
The panTo accepts LatLng object as parameters not just coordinates. Create a LatLng object before passing it to panTo method.
function clickroute(lati,long) {
map.panTo(new google.maps.LatLng(lati,long));
return false; //this will cancel your navigation
}
Your page reloads because you do not cancel the navigation event in onClick that you put in the anchor tag. See comment in code above.
And like the others say take out the map variable from this function and make map global.
you can also set a new marker on the fly:
var LatLng = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker({
content: "<h2>Hier wohne ich!</h2>",
map: map,position: results[0].geometry.location
});
map.panTo(LatLng);
You can do this:
var latLng = new google.maps.LatLng(lat_val, lng_value);
map.panTo(latLng);`
The line...
map = google.maps.Map(document.getElementById("map_canvas"));
.. is actually attempting to create a new Map within the #map_canvas Div. Since that map should already exist, you don't need that assignment statement. Just calling
map.panTo(lati,long)
should work?
Edit: Sorry, SSRide360 is correct that should be...
map.panTo(new google.maps.LatLng(lati, long));

Google Maps v3 - How to center using an address on initialize?

Using Google Maps API v3, is there a way to set the center of the map on initialize? I have a workaround using this code:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
codeAddress('germany');
}
function codeAddress(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
});
}
The only problem is that when it initializes, it centers it to the "latlng" for a split second. I'm can't figure out how to set the center in "myOptions". I though I could return "results[0].geometry.location" from the codeAddress function and pass it to myOptions, but that doesn't work.
Thanks for any help.
Update
Since I can't remove "center" altogether, I'm wondering if there's a way to pass the address to the options.
From Google API:
To initialize a Map, we first create a Map options object to contain map initialization variables.
This object is not constructed; instead it is created as an object literal. There are two required
options for every map: center and zoom.
Well a simple solution could be to initialize the map in your codeAddress function:
var geocoder, map;
function codeAddress(address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 8,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
});
}
This should solve the problem.
This is an amazing answer that really helped me get super far. The only issue now is that setCenter is no longer valid in the JavaScript API. Here's my example using fitBounds, ES6 arrow functions to access a this reference to the google map angular component, and finally implementing ngOnChanges to listen for changes to an address text field and re-render the map accordingly.
ngOnChanges(changes: SimpleChanges) {
const newFormattedAddress = changes['formattedAddress']?.currentValue;
if (!newFormattedAddress) {
return;
}
// if we received an update to the formattedAddress from the search box
const geocoder = new google.maps.Geocoder();
geocoder.geocode(
{
address: newFormattedAddress
},
(results: GeocoderResult[], status: GeocoderStatus) => {
if (status === GeocoderStatus.OK && results.length > 0) {
const firstResult = results[0].geometry;
const bounds = new google.maps.LatLngBounds();
if (firstResult.viewport) {
// Only geocodes have viewport.
bounds.union(firstResult.viewport);
} else {
bounds.extend(firstResult.location);
}
this.map.fitBounds(bounds);
}
}
);
}
External references and credit for the fitBounds code: https://kevinkreuzer.medium.com/how-to-implement-an-address-search-with-angular-and-google-maps-32a2df09f8e9

Categories

Resources