Google maps reverse geocoding returns zero_results - google-maps

I have this code where I try getting address from coords in a google map,but my phone returns status error zero_results.
I am sure my location is available because if I tested via browser and my address location for coordinates is returned.
Any ideas?
<!DOCTYPE html>
<html>
<head>
<title>Geolocation test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
div#mapdiv {
width: 500px;
height: 300px;
margin: 10px auto;
}
</style>
</head>
<body onload="">
<div id="mapdiv"></div>
<div id="msg"></div>
<div id="msg2"></div>
<script type="text/javascript">
function initMap() {
var pos2;
var map = new google.maps.Map(document.getElementById('mapdiv'), {
center: {lat: -34.397, lng: 150.644},
zoom: 12
});
var infoWindow = new google.maps.InfoWindow({map: map});
var latLng;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
pos2 = pos;
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
infoWindow.setPosition(pos);
infoWindow.setContent('La tua posizione.');
map.setCenter(pos);
}, function () {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
var geocoder = new google.maps.Geocoder;
geocoder.geocode({'latLng': pos2}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: pos2,
map: map
});
document.getElementById('msg').innerHTML = results[0].formatted_address;
} else {
document.getElementById('msg').innerHTML = 'results[1].formatted_address';
window.alert('No results found');
}
} else {
document.getElementById('msg2').innerHTML = JSON.stringify(pos2);
window.alert('Geocoder failed due to: ' + status);
}
});
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script async defer
src="http://maps.google.com/maps/api/js?key=API_KEY&callback=initMap"></script>
</body>
</html>
`

the geolocation service is asynchronous, you need to use the data (pos2) in the callback function when/where it is available. Currently you are calling the geocoder before that value is set.
proof of concept fiddle
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
pos2 = pos;
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('La tua posizione.');
// call reverse geocoder with location returned by geolocation service
var geocoder = new google.maps.Geocoder;
geocoder.geocode({
'latLng': pos2
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: pos2,
map: map
});
infoWindow.setContent('La tua posizione.<br>'+ results[0].formatted_address);
} else {
document.getElementById('msg').innerHTML = 'results[1].formatted_address';
window.alert('No results found');
}
} else {
document.getElementById('msg2').innerHTML = JSON.stringify(pos2);
window.alert('Geocoder failed due to: ' + status);
}
});
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
code snippet:
div#mapdiv {
width: 500px;
height: 300px;
margin: 10px auto;
}
<div id="mapdiv"></div>
<div id="msg"></div>
<div id="msg2"></div>
<script type="text/javascript">
function initMap() {
var pos2;
var map = new google.maps.Map(document.getElementById('mapdiv'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 12
});
var infoWindow = new google.maps.InfoWindow({
map: map
});
var latLng;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
pos2 = pos;
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(pos);
infoWindow.setPosition(pos);
infoWindow.setContent('La tua posizione.');
var geocoder = new google.maps.Geocoder;
geocoder.geocode({
'latLng': pos2
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: pos2,
map: map
});
infoWindow.setContent('La tua posizione.<br>'+ results[0].formatted_address);
} else {
document.getElementById('msg').innerHTML = 'results[1].formatted_address';
window.alert('No results found');
}
} else {
document.getElementById('msg2').innerHTML = JSON.stringify(pos2);
window.alert('Geocoder failed due to: ' + status);
}
});
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script async defer src="https://maps.google.com/maps/api/js?callback=initMap"></script>

Related

setCenter in google map api is not working. map is invisible

I have been working on Google map project and encountered this issue.
I wanted to use setCenter method to relocate map center. I only can see the gray map instead. I think it's supposed to be working find but I don't know what is wrong
Here is how it looks likeenter image description here
enter code here
var map;
var marker;
function initMap(){
var options = {
center: new google.maps.LatLng(37.4989885,127.03282719999993),
zoom : 8
};
map = new google.maps.Map(document.getElementById('map'), options);
marker = new google.maps.Marker({
position : {lat:37.4989885,lng:127.03282719999993},
map : map
});
}
function changePosition(altitude, longitude){
map.setCenter(new google.maps.LatLng(altitude,longitude));
marker.setPosition(new google.maps.LatLng(altitude,longitude));
}
$(function() {
var url = "tourXML";
$.ajax({
type : "GET",
url : url,
dataType : "text",
success : function(data) {
var temp = $.trim(data);
obj = JSON.parse(temp);
var longitude = parseFloat(obj.longitude);
var altitude = parseFloat(obj.altitude);
changePosition(altitude, longitude);
$("#altitude").html(obj.altitude);
$("#longitude").html(obj.longitude);
},
error : function() {
alert("error.");
}
});
});
You can use this code Modified it as per you need
map.setCenter(21.219381 ,72.840128);
or
map.setCenter(pos);
enter code here
function initMap ()
{
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {lat: 21.219381, lng: 72.840128}
});
var geocoder = new google.maps.Geocoder;
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
var infowindow = new google.maps.InfoWindow;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
geocoder.geocode({'location': pos}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
console.log(JSON.stringify(results[0]));
map.setZoom(11);
var marker = new google.maps.Marker({
position: pos,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
map.setCenter(pos);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}

Getting values of cursor from indexedDB

I'm trying to put markers on a google location map API using data I put on an inedexedDB. I'm able to put the markers accurately using the data I get from the DB, but the markers' infowindow doesn't get them accurately.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<style type="text/css">
#map {
width: 700px;
height: 700px;
}
</style>
</head>
<body>
<div id="map"></div>
<button onclick="showMarker()">Show Markers </button>
<script type="text/javascript">
//prefixes of implementation that we want to test
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
//prefixes of window.IDB objects
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.")
}
var db;
var request = window.indexedDB.open("mapDB", 1);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(11.980433, 121.918866),
mapTypeId: google.maps.MapTypeId.HYBRID
});
const locData = [
{ id: "00-01", name: "Boracay", lat: 11.980433, lng: 121.918866 },
{ id: "00-02", name: "Baguio City", lat: 16.402333, lng: 120.596007 },
{ id: "00-03", name: "Isdaan", lat: 15.475479, lng: 120.596349 },
{ id: "00-04", name: "Mount Pinatubo", lat: 15.142973, lng: 120.349302 }
];
request.onerror = function(event) {
console.log("error: ");
};
request.onsuccess = function(event) {
db = request.result;
console.log("success: "+ db);
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("location", {keyPath: "id"});
for (var i in locData) {
objectStore.add(locData[i]);
}
db.onsuccess = function(event) {
showMarker();
};
}
function showMarker() {
var infowindow = new google.maps.InfoWindow();
var marker, i;
var objectStore = db.transaction("location").objectStore("location");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(cursor.value.lat, cursor.value.lng),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(cursor.value.name);
infowindow.open(map, marker);
}
})(marker, i));
cursor.continue();
}
};
}
</script>
</body>
</html>
I have tried searching and reading other sources but I can't seem to find what's the problem. Help is very much appreciated.
This is a duplicate of Google Maps JS API v3 - Simple Multiple Marker Example. You need function closure on the name of the marker.
function showMarker() {
var infowindow = new google.maps.InfoWindow();
var marker;
var objectStore = db.transaction("location").objectStore("location");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(cursor.value.lat, cursor.value.lng),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, name) {
return function() {
infowindow.setContent(name);
infowindow.open(map, marker);
}
})(marker, cursor.value.name));
cursor.continue();
}
};
}
proof of concept fiddle

Google API to map nearby properties in Salesforce

I asked this question originally in the Salesforce StackExchange, but was redirected here, since it's more of a Google API question than a Salesforce question.
Right now I have the following code, which creates a marker at the location of the property on a visualforce page that has an embedded Google Map. When the user clicks on the marker, an info window appears with information on the property.
<apex:page standardController="Property__c">
<head>
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var myOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
scrollwheel: false
}
var map;
var marker;
var geocoder = new google.maps.Geocoder();
var address = "{!Property__c.Property_Address__c}, " + "{!Property__c.City__c}, " + "{!Property__c.State__c} " + "{!Property__c.Zip_Postal_Code__c}}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Property__c.Name}</b><br>{!Property__c.Property_Address__c}<br>{!Property__c.City__c}, {!Property__c.State__c} {!Property__c.Zip_Postal_Code__c}"
});
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setTilt(45);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Property__c.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
}
} else {
$('#map').css({
'height': '15px'
});
$('#map').html("Oops! {!Property__c.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});
</script>
<style>
#map {
font-family: Arial;
font-size: 12px;
line-height: normal !important;
height: 800px;
background: transparent;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</apex:page>
This is working just fine. But I am trying to modify it to also show properties nearby to this property. I have gotten as far as using an SOQL query to find these properties, pass their addresses into an array, geocode these addresses and set a marker at each geocoordinate. All of that works just swell.
Where I've been stuck, is in displaying the infowindow that appears when the user clicks one of these markers. Not only can I not create an infowindow for the NEW markers, but the infowindow for the OLD "main" marker is breaking as well. In fact, even if I comment the infowindow and listener events for the new markers, the original is still broken. These infowindows need to display different information than the infowindow for the "main" marker. Here is my modified code:
$(document).ready(function() {
var myOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
scrollwheel: false
}
var map;
var marker;
var marker2;
var geocoder = new google.maps.Geocoder();
var address = "{!Property__c.Property_Address__c}, " + "{!Property__c.City__c}, " + "{!Property__c.State__c} " + "{!Property__c.Zip_Postal_Code__c}}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Property__c.Name}</b><br>{!Property__c.Property_Address__c}<br>{!Property__c.City__c}, {!Property__c.State__c} {!Property__c.Zip_Postal_Code__c}"
});
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setTilt(45);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Property__c.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
//several markers
//Get Geos
var geos = [];
var idy = 0; <
apex: repeat value = "{!getgeoList}"
var = "m" >
geos[idy++] = "{!m}"; <
/apex:repeat>
for (var i = 0; i < geos.length; ++i) {
console.log('geo' + geos[i] + 'out of' + geos.length);
geocodeAddress(geos[i]);
}
function geocodeAddress(location) {
geocoder.geocode({
'address': location
}, function(results, status) {
// alert(status);
if (status == google.maps.GeocoderStatus.OK) {
// alert(results[0].geometry.location+location);
createMarker(results[0].geometry.location, location);
} else {
alert("some problem in geocode" + status);
}
});
}
function createMarker(latlng, html) {
marker2 = new google.maps.Marker({
position: latlng,
map: map
});
addIinfo(marker2, html);
}
function addInfo(marker2, html) {
var infowindow2 = new google.maps.InfoWindow({
content: html
});
marker2.addListener(marker2, 'click', function() {
infowindow2.open(marker2.get('map'), marker2);
});
}
}
} else {
$('#map').css({
'height': '15px'
});
$('#map').html("Oops! {!Property__c.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});
I changed marker2.addListener to google.maps.event.addListener. This worked, except that my original marker was showing the same information as the marker2 markers. When I changed the marker2 icon to blue, I realized that this was because it was putting a marker2 marker over the original marker. So I changed i = 0 to i=1 in my for loop, and now my code works just great! :)
Here is my new code:
$(document).ready(function() {
var myOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.HYBRID,
mapTypeControl: true,
scrollwheel: false
}
var map;
var marker;
var marker2;
var geocoder = new google.maps.Geocoder();
var address = "{!Property__c.Property_Address__c}, " + "{!Property__c.City__c}, " + "{!Property__c.State__c} " + "{!Property__c.Zip_Postal_Code__c}}";
var infowindow = new google.maps.InfoWindow({
content: "<b>{!Property__c.Name}</b><br>{!Property__c.Property_Address__c}<br>{!Property__c.City__c}, {!Property__c.State__c} {!Property__c.Zip_Postal_Code__c}"
});
geocoder.geocode({
address: address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map
map = new google.maps.Map(document.getElementById("map"), myOptions);
map.setTilt(45);
//center map
map.setCenter(results[0].geometry.location);
//create marker
marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: "{!Property__c.Name}"
});
//add listeners
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(infowindow, 'closeclick', function() {
map.setCenter(marker.getPosition());
});
//several markers
//Get Geos
var geos = [];
var idy=0;
<apex:repeat value="{!getgeoList}" var="m">
geos[idy++]="{!m}";
</apex:repeat>
for (var i = 1; i < geos.length; ++i) {
console.log('geo' + geos[i] + 'out of' + geos.length);
geocodeAddress(geos[i]);
}
function geocodeAddress(location) {
geocoder.geocode({
'address': location
}, function(results, status) {
// alert(status);
if (status == google.maps.GeocoderStatus.OK) {
// alert(results[0].geometry.location+location);
createMarker(results[0].geometry.location, location);
} else {
alert("some problem in geocode" + status);
}
});
}
function createMarker(latlng, html) {
marker2 = new google.maps.Marker({
position: latlng,
map: map,
icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
addInfo(marker2,html);
}
function addInfo(marker2,html) {
var infowindow2 = new google.maps.InfoWindow({
content: html });
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map, marker2);
});
}
}
} else {
$('#map').css({
'height': '15px'
});
$('#map').html("Oops! {!Property__c.Name}'s billing address could not be found, please make sure the address is correct.");
resizeIframe();
}
});
function resizeIframe() {
var me = window.name;
if (me) {
var iframes = parent.document.getElementsByName(me);
if (iframes && iframes.length == 1) {
height = document.body.offsetHeight;
iframes[0].style.height = height + "px";
}
}
}
});

Google Maps API - get water body name

How can i get Water body name from google map api?
For example, when i click on map i choose "What's here?" popup will appear with lake name and coordinates. I need that name.
Lake Michigan is in the Places API at those coordinates. The "name" is "Lake Michigan / Michigan City" however.
Using the Google Maps Javascript API v3 Places Library:
code snippet:
var map;
var infowindow;
var service;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(43.4501005, -87.2220187),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: map.getCenter(),
radius: 500
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log("OK:" + results.length)
for (var i = 0; i < results.length; i++) {
console.log(results[i]);
var marker = createMarker(results[i]);
if (i == 0) google.maps.event.trigger(marker, 'click');
}
}
}
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 + "<br>place_id:" + place.place_id);
infowindow.open(map, this);
service.getDetails({
placeId: place.place_id
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address + '</div>');
infowindow.open(map, this);
});
google.maps.event.trigger(marker, 'click');
}
});
});
return marker;
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="map_canvas"></div>

How to drag marker and click to set at the same time in Google Maps API v3?

I'm new in Google Maps API v3, I'm trying to add click event listener to re-set the marker, but I want have the posibility to drag the marker too.
Actually I only can drag the marker, this is my code:
var lat = null;
var lng = null;
var map = null;
var geocoder = null;
var marker = null;
jQuery(document).ready(function(){
lat = jQuery('#lat').val();
lng = jQuery('#long').val();
jQuery('#pasar').click(function(){
codeAddress();
return false;
});
initialize();
});
function initialize() {
geocoder = new google.maps.Geocoder();
if(lat !='' && lng != '')
{
var latLng = new google.maps.LatLng(lat,lng);
}
else
{
var latLng = new google.maps.LatLng(11.027113, -63.862023);
}
var myOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
marker = new google.maps.Marker({
map: map,
position: latLng,
draggable: true
});
updatePosition(latLng);
}
function codeAddress() {
var address = document.getElementById("direccion").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);
updatePosition(results[0].geometry.location);
google.maps.event.addListener(marker, 'dragend', function(){
updatePosition(marker.getPosition());
});
} else {
alert("No podemos encontrar la direccion, error: " + status);
}
});
}
function updatePosition(latLng)
{
jQuery('#lat').val(latLng.lat());
jQuery('#long').val(latLng.lng());
}
I tried to add the following code:
myListener = google.maps.event.addListener(map, 'click', function(event) {
if(marker){marker.setMap(null)}
placeMarker(event.latLng);
google.maps.event.removeListener(myListener);
});
But it does not work.
I want to place the marker with both options, dragging and click. How I can achieve that in my code?
Thanks!
There is no placeMarker function in your code, and not sure why you only want the marker placed on the first click on the map (you are removing the listener after that). This is what I think you want:
var lat = null;
var lng = null;
var map = null;
var geocoder = null;
var marker = null;
var myListener = null;
jQuery(document).ready(function() {
lat = jQuery('#lat').val();
lng = jQuery('#long').val();
jQuery('#pasar').click(function() {
codeAddress();
return false;
});
initialize();
});
function initialize() {
geocoder = new google.maps.Geocoder();
if (lat != '' && lng != '') {
var latLng = new google.maps.LatLng(lat, lng);
} else {
var latLng = new google.maps.LatLng(11.027113, -63.862023);
}
var myOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
marker = new google.maps.Marker({
map: map,
position: latLng,
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function() {
updatePosition(marker.getPosition());
});
updatePosition(latLng);
google.maps.event.addListener(map, 'click', function(event) {
if (marker) {
marker.setPosition(event.latLng)
} else {
marker = new google.maps.Marker({
map: map,
position: event.latLng,
draggable: true
});
}
updatePosition(event.latLng);
});
}
function codeAddress() {
var address = document.getElementById("direccion").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);
updatePosition(results[0].geometry.location);
google.maps.event.addListener(marker, 'dragend', function() {
updatePosition(marker.getPosition());
});
} else {
alert("No podemos encontrar la direccion, error: " + status);
}
});
}
function updatePosition(latLng) {
jQuery('#lat').val(latLng.lat());
jQuery('#long').val(latLng.lng());
}
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="lat" value="42" />
<input id="long" value="-85" />
<input id="pasar" type="button" value="geocode" />
<input id="direccion" value="New York, NY" />
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>