Google maps Geocoder and Marker not working - javascript

I'm trying to take an address in a for loop and get the latitude and longitude of that address and create a marker with the lat/long values.
I have the address converting to lat/long but I cannot get the "new Marker" to take the values.
Any suggestions?
var latitude;
var longitude;
var myLatLng;
for (i = 0; i < locations.length; i++) {
var geocoder = new google.maps.Geocoder();
var BuisAddress = locations[i][1];
geocoder.geocode({ 'address': BuisAddress }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
}
});
myLatLng = new google.maps.LatLng(latitude, longitude);
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
**** 1st UPDATE ****
if I do that, then only one marker shows up when I have multiple addresses and the marker popup doesn't work. If I do the following, then all three markers show up, but still none of clickable popup's work.
var geocoder = new google.maps.Geocoder();
BuisAddress = locations[i][1];
geocoder.geocode({ 'address': BuisAddress }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
myLatLng = new google.maps.LatLng(latitude, longitude);
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
}
});
myLatLng = new google.maps.LatLng(latitude,longitude);
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
var str = encodeURI(locations[i][1]).replace(",", "");
var address = str.replace(/%20/g, "+");
var infowindow = new google.maps.InfoWindow();

You can try this way (i added a marker vector for manage the vector collection)
var latitude;
var longitude;
var myLatLng;
myMarker = []
for (i = 0; i < locations.length; i++) {
geocoder.geocode({ 'address': BuisAddress }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
myLatLng = new google.maps.LatLng(latitude, longitude);
marker[i] = new google.maps.Marker({
position: myLatLng,
map: map
});
}
});
google.maps.event.addListener(marker[i], 'click', (function(marker[i], i) {
return function() {
var str = encodeURI(locations[i][1]).replace(",", "");
var address = str.replace(/%20/g, "+");
var infowindow = new google.maps.InfoWindow();
}
}));
}

If anyone is wondering how I did it, here it is!
function geocodeAddress(locations, i) {
var title = locations[i][0];
var address = locations[i][1];
var url = locations[i][2];
var latitude;
var longitude;
geocoder.geocode({
'address': locations[i][1]
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
var marker = new google.maps.Marker({
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map,
position: results[0].geometry.location,
title: title,
animation: google.maps.Animation.DROP,
address: address,
url: url,
latitude: latitude,
longitude: longitude
})
infoWindow(marker, map, title, address, url, latitude, longitude);
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
} else {
alert("geocode of " + address + " failed:" + status);
}
});
}
function infoWindow(marker, map, title, address, url, latitude, longitude) {
google.maps.event.addListener(marker, 'click', function() {
var html ="html code here...";
iw = new google.maps.InfoWindow({
content: html,
maxWidth: 350
});
iw.open(map, marker);
});
}
function createMarker(results) {
var marker = new google.maps.Marker({
icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
map: map,
position: results[0].geometry.location,
title: title,
animation: google.maps.Animation.DROP,
address: address,
url: url
})
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
infoWindow(marker, map, title, address, url);
return marker;
}

Related

Why is my map not displaying the place name in the map after getting the current location?

I have made a map with getting the current location,inside the getPosition is getting also the place name which I also made a reverse geocoding that returns the place name from a coordinate, I wonder what's wrong my code that it did not return the place name and even the marker with my code for reverse geocoding.
In the console I get this
<p id="curr" style="">current lat lng</p>
function getPosition() {
navigator.geolocation.getCurrentPosition(position => {
currentLatLon = [position.coords.latitude, position.coords.longitude];
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(
document.getElementById('map'), {
center: new google.maps.LatLng(...currentLatLon),
zoom: 20
});
var geocoder = new google.maps.Geocoder();
service = new google.maps.places.PlacesService(map);
document.getElementById("curr").innerHTML=currentLatLon;
geocodeLatLng(geocoder,map,infowindow);
});
}
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('curr').value;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}

Get address from latitude & longitude

Help to find,how can I show the address dynamic in infowindow (when marker click)
I have to include the Latitud& longitude,but because of loop its shows only one address for all marker,but here i need to display specific address for individual marker
var infoWindow = new google.maps.InfoWindow();
var geocoder;
var map;
var i,j;
var js_lats = ['11.798880','13.0826802','12.975444'];
var js_longs =['77.827760','80.2707184','80.220642'];
if(js_lats.length>0)
{
for (i = 0; i < js_lats.length; i++) {
var latlng = new google.maps.LatLng(js_lats[i],js_longs[i]);
var geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
loc= results[1].formatted_address;
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 10
}
var geocode = document.getElementById('address1').value;
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
geocoder = new google.maps.Geocoder();
document.getElementById("dis").setAttribute('style','visibility:visible;');
geocoder.geocode( { 'address': loc},
function(results, status)
{
map.fitBounds(results[0].geometry.viewport);
var icon = "Markers/letter_m.png";
var infoWindow = new google.maps.InfoWindow();
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
});
var loc1 = loc;
(function (marker){
google.maps.event.addListener(marker, "click", function (e) {{
infoWindow.setContent("<span class='lm_loc_detail_trk'>Location :</span><span class='lm_addr_detail_trk'>"+loc1+ "</span></div>");
infoWindow.open(map, marker);
}});})(marker);
var listener = google.maps.event.addListener(map, "idle", function () {
map.setZoom(6);
google.maps.event.removeListener(listener);
});
}
else{alert('Geocode was not successful for the following reason: ' + status);
}
});}}});}}

how to update google map marker base on latitude and longitude from input field

I have a textarea field that user can type or paste the address into and then I use google geocoder to convert those addresses into latitude and longitude and display them on the latitude and longitude form fields.Also the user can drag to relocate the marker for specific address. My problem here is after it converted into latitude and longitude, I want the google map marker update its location automatically on the default latitude and longitude.
Here is the code for converting from address to latitude and longitude.
function getAddress() {
var geocoder = new google.maps.Geocoder();
var addr = document.getElementById('ClinicAddress').value;
geocoder.geocode({'address': addr}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
document.getElementById('ClinicLatitude').value = latitude;
document.getElementById('ClinicLongitude').value = longitude;
}
});
}
and here is my code for dragging google map marker
function initialize() {
var $latitude = document.getElementById('ClinicLatitude');
var $longitude = document.getElementById('ClinicLongitude');
//default latitude and longitude for Tokyo JP
var latitude = 35.7061767;
var longitude = 139.7340773;
document.addEventListener('input', function() {
if($latitude.value !== '' && $longitude.value !== '') {
latitude = $latitude.value;
longitude = $longitude.value;
alert(latitude + "," + longitude);
}
});
var zoom = 15;
var LatLng = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: zoom,
center: LatLng,
panControl: false,
zoomControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('google_map'), mapOptions);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: 'Drag to specify your address',
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function (marker) {
var latLng = marker.latLng;
$latitude.value = latLng.lat();
$longitude.value = latLng.lng();
});
}
initialize();
Ok, finally I found a solution for this. Any better solution is welcome.
function getAddress() {
var geocoder = new google.maps.Geocoder();
var addr = document.getElementById('ClinicAddress').value;
geocoder.geocode({'address': addr}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
document.getElementById('ClinicLatitude').value = latitude;
document.getElementById('ClinicLongitude').value = longitude;
//call initialize to update new location with latitude and longitude
initialize(latitude,longitude);
}
});
}
//getting google map api on form
function initialize(latitude,longitude) {
var $latitude = document.getElementById('ClinicLatitude');
var $longitude = document.getElementById('ClinicLongitude');
//default latitude and longitude for Tokyo JP
//var latitude = 35.7061767;
//var longitude = 139.7340773;
var zoom = 15;
var LatLng = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: zoom,
center: LatLng,
panControl: false,
zoomControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('google_map'), mapOptions);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: 'Drag to specify your address',
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function (marker) {
var latLng = marker.latLng;
$latitude.value = latLng.lat();
$longitude.value = latLng.lng();
});
}
//set default latitude and longitude
initialize('35.7061767','139.7340773');

how to close info window when other info window open in google map javascript

its working fine but i have one problem which is that when i open a info window its opened but when i open other info window. the last one info window still opened. but i want to close it when we open new inf window
<script>
window.onload = getMyLocation;
var geocoder;
var map;
function getMyLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation);
} else {
alert("Oops, no geolocation support");
}
}
//This function is inokved asynchronously by the HTML5 geolocation API.
function displayLocation(position) {
//The latitude and longitude values obtained from HTML 5 API.
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
//Creating a new object for using latitude and longitude values with Google map.
var latLng = new google.maps.LatLng(latitude, longitude);
showMap(latLng);
addNearByPlaces(latLng);
createMarker(latLng);
//Also setting the latitude and longitude values in another div.
// var div = document.getElementById("location");
//div.innerHTML = "You are at Latitude: " + latitude + ", Longitude: " + longitude;
}
function showMap(latLng) {
geocoder = new google.maps.Geocoder();
var markers = [];
//Setting up the map options like zoom level, map type.
var mapOptions = {
center: latLng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Creating the Map instance and assigning the HTML div element to render it in.
map = new google.maps.Map(document.getElementById("googlemap"), mapOptions);
// Create the search box and link it to the UI element.
}
function addNearByPlaces(latLng) {
var nearByService = new google.maps.places.PlacesService(map);
var request = {
location: latLng,
radius: 500,
types: ['atm']
};
nearByService.nearbySearch(request, handleNearBySearchResults);
}
function handleNearBySearchResults(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
var place = results[i];
createMarker(place.geometry.location, place);
}
}
function createMarker(latLng, placeResult) {
var markerOptions = {
position: latLng,
map: map,
animation: google.maps.Animation.DROP,
clickable: true
}
//Setting up the marker object to mark the location on the map canvas.
var marker = new google.maps.Marker(markerOptions);
if (placeResult) {
var content = "<b>Name : </b>"+placeResult.name+"<br/><b>Address : </b>"+placeResult.vicinity+"<br/><b>Type : </b>"+placeResult.types+"<br/> Rating : "+placeResult.rating+"<br/>" ;
addInfoWindow(marker, latLng, content);
}
else {
var content = "You are here: ";
addInfoWindow(marker, latLng, content);
}
}
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);
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
<!-- alert("Latitude: " + latitude + "\nLongitude: " + longitude); -->
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
var latLngs = new google.maps.LatLng(latitude, longitude);
addNearByPlaces(latLngs);
createMarker(latLngs);
});
}
function addInfoWindow(marker, latLng, content) {
var infoWindowOptions = {
content: content,
position: latLng
};
var infowindow = new google.maps.InfoWindow(infoWindowOptions);
google.maps.event.addListener(marker, 'click', function() {
if(!marker.open){
infowindow.open(map,marker);
marker.open = true;
}
else{
infowindow.close();
marker.open = false;
}
});
}
</script>
I use something like this for closing all infoWindows:
infoWindows = []; //variable to store all infoWindows
function createMarker( map, latlng, title, content, icon ) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: icon,
title: title
});
var infoWindow = new google.maps.InfoWindow({
content: content
});
infoWindows.push( infoWindow );
google.maps.event.addListener(marker, 'click', function () {
closeAllInfoWindows();
infoWindow.open(map, marker);
});
}
function closeAllInfoWindows() {
for (var i=0;i<infoWindows.length;i++) {
infoWindows[i].close();
}
}

Google Maps Geocode not working (no markers)

I have a webpage to find latitude, longitude, and get a marker for that position. I use Google Maps.
My webpage get 2 addresses from user input, address 1 and address 2, and calls codeAddress()
<div id="panel">
<input id="address1" type="textbox" value="">
<input id="address2" type="textbox" value="">
<input type="button" value="find!" onclick="codeAddress()">
</div>
This is my JavaScript code:
var map;
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;
function initialize() {
var latlng = new google.maps.LatLng(-7.275920, 112.791871);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var gc = google.maps.Geocoder();
gc.geocode({
'address': address1
}, function (res1, status) {
if (status == google.maps.GeocoderStatus.OK) {
gc.geocode({
'address': address2
}, function (res2, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: res1[0].geometry.location,
map: map
});
new google.maps.Marker({
position: res2[0].geometry.location,
map: map
});
}
});
}
});
}
When I click the button find, I didn’t get the markers. Can any body help me?
Modify the codeAddress function like this:
function codeAddress() {
var gc = new google.maps.Geocoder(); // notice new keyword
initialize(); // Calling initialize. If you skip it, maps aren't loading
gc.geocode({
'address': address1
}, function(res1, status) {
if (status == google.maps.GeocoderStatus.OK) {
gc.geocode({
'address': address2
}, function(res2, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: res1[0].geometry.location,
map: map
});
new google.maps.Marker({
position: res2[0].geometry.location,
map: map
});
}
});
}
});
Make sure both of the inputs have some value to test it.
Demo: http://jsfiddle.net/lotusgodkk/GCu2D/213/
update the address variables from the form when the function runs
function codeAddress() {
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;
check for status != OK
} else alert("Geocode failed of " + address1 + ", status=" + status);
use "new" before the google maps Geocoder constructor
var gc = new google.maps.Geocoder();
remove existing markers before displaying new ones so the markers don't accumulate on the map
if (marker1 && marker1.setMap) marker1.setMap(null);
complete code:
var map = null;
var marker1 = null;
var marker2 = null;
var gc = new google.maps.Geocoder();
function initialize() {
var latlng = new google.maps.LatLng(-7.275920, 112.791871);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress();
}
function codeAddress() {
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;
gc.geocode({
'address': address1
}, function (res1, status) {
if (status == google.maps.GeocoderStatus.OK) {
gc.geocode({
'address': address2
}, function (res2, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (marker1 && marker1.setMap) marker1.setMap(null);
marker1 = new google.maps.Marker({
position: res1[0].geometry.location,
map: map
});
if (marker2 && marker2.setMap) marker2.setMap(null);
marker2 = new google.maps.Marker({
position: res2[0].geometry.location,
map: map
});
} else alert("Geocode failed of " + address2 + ", status=" + status);
});
} else alert("Geocode failed of " + address1 + ", status=" + status);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
working fiddle

Categories

Resources