Get location address from Latitude and Longitude in google maps - javascript

I want after click on google map and getting Latitude and Longitude get location place from they and put it (address) in filed input#searchTextField. What do i do?
I tried as, but don't work for me:
DEMO: http://jsfiddle.net/DXkZJ/
<input id="searchTextField" type="text" size="50" style="text-align: left;width:357px;direction: ltr;">
<div id="map_canvas" style="height: 350px;width: 500px;margin: 0.6em;"></div>
$(function () {
var lat = 44.88623409320778,
lng = -87.86480712897173,
latlng = new google.maps.LatLng(lat, lng),
image = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png';
//zoomControl: true,
//zoomControlOptions: google.maps.ZoomControlStyle.LARGE,
var mapOptions = {
center: new google.maps.LatLng(lat, lng),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.TOP_left
}
},
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions),
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: image
});
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input, {
types: ["geocode"]
});
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(autocomplete, 'place_changed', function (event) {
infowindow.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
moveMarker(place.name, place.geometry.location);
alert(place.name);
$('.MapLat').val(place.geometry.location.lat());
$('.MapLon').val(place.geometry.location.lng());
});
google.maps.event.addListener(map, 'click', function (event) {
$('.MapLat').val(event.latLng.lat());
$('.MapLon').val(event.latLng.lng());
alert(event.latLng.place.name)
});
$("#searchTextField").focusin(function () {
$(document).keypress(function (e) {
if (e.which == 13) {
return false;
infowindow.close();
var firstResult = $(".pac-container .pac-item:first").text();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
"address": firstResult
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat(),
lng = results[0].geometry.location.lng(),
placeName = results[0].address_components[0].long_name,
latlng = new google.maps.LatLng(lat, lng);
moveMarker(placeName, latlng);
$("input").val(firstResult);
alert(firstResult)
}
});
}
});
});
function moveMarker(placeName, latlng) {
marker.setIcon(image);
marker.setPosition(latlng);
infowindow.setContent(placeName);
//infowindow.open(map, marker);
}
});​

Ok, so firstly you need reverse geocoding, not regular geocoding, because you are going from a latitude/longitude into an address rather than the other way around (see reference). Secondly your key listener would never do anything because it almost immediately states return false; in this case you probably want event.stopPropogation(). Furthermore google maps will intercept your mouse clicks at a greater depth in the DOM tree than document, so the event will never be listened that highly anyway.
So what I did was to change your geocode into a reverse geocode, as well as move the code in the document listener into the google listener. If you wanted to retain the behaviour of the listener being added on focus, you can simply create a new listener on the map object. Here is a working jsfiddle demonstrating these changes, hopefully this helps.

Take a look at the gmap developers api.
for topic Reverse Geocoding (Address Lookup) .
You will got your answer.

Just add this code after moveMarker() function
$("#map_canvas").click(function() {
$("#searchTextField").val($(".MapLat").val() +", "+$(".MapLon").val());
});
Hope, this is what you needed :)

Related

Google maps v3 not a LatLngBounds or LatLngBoundsLiteral: not an Object name: "InvalidValueError"

Not the best with javascript and got some trouble with some google maps code but it is sporadic on MS Edge but consistent on Chrome and the markers will not load. On edge if you keep request the page sometimes it works but more than often fails.
ERROR: not a LatLngBounds or LatLngBoundsLiteral: not an Object name:
"InvalidValueError"
script is called using below code
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXX&libraries=places"></script>```
<script async type="text/javascript" src="{{media url='scripts/store-locator.js'}}"></script>```
require(["jquery"], function ($) {
$(document).ready(function () {
initialize();
});
var geocoder,
map,
markers = [],
infowindow = new google.maps.InfoWindow(),
bounds = new google.maps.LatLngBounds(),
marker, i;
var locations = [
{ id: 1, name: 'Store1', lat: 58.482514, lng: -1.784622 },
{ id: 2, name: 'Store2', lat: 54.687925, lng: 0.312584 }
];
function initialize() {
// set the default google map settings
geocoder = new google.maps.Geocoder();
directionsDisplay = new google.maps.DirectionsRenderer({ draggable: true });
var latlng = new google.maps.LatLng(52.727440, -1.543299);
var myOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// register the google map elements
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// register the directions display
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions'));
addMarkers();
map.fitBounds(bounds);
google.maps.event.addListenerOnce(map, 'tilesloaded', function () {
// setup control position
control = document.getElementById('store-selector');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(control);
control.style.display = 'block';
});
}
// add the markers from the array to the map
function addMarkers() {
$.each(locations, function (key, value) {
// create the marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(this.lat, this.lng),
map: map,
name: this.name
});
// add the marker to the cached array
markers.push(marker);
bounds.extend(marker.position);
// add the event listerner for the marker click function
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
// info window display
map.setZoom(16);
map.setCenter(marker.getPosition());
}
})(marker, i));
});
}
});```
Ok I think I have resolved it thanks to geocodezip who suggested a timing issue. was erroring on $(document).ready(function () {
initialize();
});
I've moved this to the bottom of the file and it seems to be running all good now..

Google maps api v3 not loading in maps

I have a problem with google maps, I have tried to just to set up a normal map, but nothing works all I get is this image:
And this is my code for this:
(function ($) {
var marker;
var map;
var iconBase = 'https://maps.google.com/mapfiles/ms/icons/';
var infowindow;
function initialize() {
getCoordinate(function (location) {
setUpMap(location.latitude, location.longitude);
});
}
function setUpMap(lat, long)
{
var myLatlng = new google.maps.LatLng(lat, long);
var mapOptions = {
zoom: 8,
center: myLatlng,
mapTypeControl: false,
streetViewControl: false,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress();
}
function codeAddress()
{
//Resellers is a global varaible that holds all the resellers addresses
Object.keys(resellers).forEach(function(key){
var reseller = resellers[key];
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(reseller.lat, reseller.lng),
icon: iconBase + 'green-dot.png'
});
(function (marker) {
// add click event
google.maps.event.addListener(marker, 'click', function () {
if (infowindow) {
infowindow.close();
}
infowindow = new google.maps.InfoWindow({
title: key,
content: '<div style="color: black; height: 150px;">' + reseller.address + '</div>'
});
infowindow.open(map, marker);
});
})(marker);
gmaerksp.push(marker);
});
}
function getCoordinate(callback) {
navigator.geolocation.getCurrentPosition(
function (position) {
var returnValue = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
};
var location = returnValue;
callback(location);
}
);
}
google.maps.event.addDomListener(window, 'load', initialize);
}(jQuery));
#map-canvas{
width: 1200px;
height: 600px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
And I have no idea why the map is not loading, the markers is loading as it should. But as you can see, the zoom tools is not correctly loading either. So you guys have any idea what is wrong? I have tested with change the div size to but it still loads the same.
Well after more debugging, I found the answer! It seems like google maps can't be inserted with wordpress shortcode. I don't know why, but as soon as I move it out to it is own template instead it works like a charm.
So if any other persons have the same problem out there, and have put there google maps in a shortcode, try to move it out from there and see if it works.

Doing a Google Maps reverse geocode and displaying the result as part as HTML content inside an infowindow

I have put together this script (note: I'm using jQuery 1.11.2) that gets lat long coordinates from a PHP operation (used for something else) and displays a map with a customized marker and infowindow that includes HTML for formatting the information that is displayed.
<script src="https://maps.googleapis.com/maps/api/js?v=3.20&sensor=false"></script>
<script type="text/javascript">
var maplat = 41.36058;
var maplong = 2.19234;
function initialize() {
// Create a Google coordinate object for where to center the map
var latlng = new google.maps.LatLng( maplat, maplong ); // Coordinates
var mapOptions = {
center: latlng,
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
streetViewControl: false,
zoomControl: false,
mapTypeControl: false,
disableDoubleClickZoom: true
};
map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
// CREATE AN INFOWINDOW FOR THE MARKER
var content = 'This will show up inside the infowindow and it is here where I would like to show the converted lat/long coordinates into the actual, human-readable City/State/Country'
; // HTML text to display in the InfoWindow
var infowindow = new google.maps.InfoWindow({
content: content,maxWidth: 250
});
var marker = new google.maps.Marker( {
position: latlng,
map: map,
title: "A SHORT BUT BORING TITLE",
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
infowindow.open(map,marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
What I'm trying to achieve is to do a reverse geocode on the coordinates stored in the latlng variable and get back the results of that in a "City, State, Country" format and insert that into the HTML for the informarker stored in the "content" variable.
Have tried multiple approaches without success. Please note that I've deliberately left out the reverse geocoding script I tried to use for clarity purposes.
Edit: I've adjusted the script presented here to comply with the rules about it being clear, readable and that it actually should work. I also include a link to a CodePen so that you can see it in action: Script on CodePen
Regarding including the script for reverse geocoding, what I did was a disaster, only breaking the page and producing "undefined value" errors. I'd like to learn the correct way of doing this by example, and that's where the wonderful StackOverflow community comes in. Thanks again for your interest in helping me out.
Use a node instead of a string as content , then you may place the geocoding-result inside the content, no matter if the infoWindow is already visible or not or when the result is available(it doesn't even matter if the InfoWindow has already been initialized, a node is always "live").
Simple Demo:
function initialize() {
var geocoder = new google.maps.Geocoder(),
latlng = new google.maps.LatLng(52.5498783, 13.42520);
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 18,
center: latlng
}),
marker = new google.maps.Marker({
map: map,
position: latlng
}),
content = document.createElement('div'),
infoWin = new google.maps.InfoWindow({
content: content
});
content.innerHTML = '<address>the address should appear here</address>';
google.maps.event.addListener(marker, 'click', function() {
infoWin.open(map, this);
});
geocoder.geocode({
location: latlng
}, function(r, s) {
if (s === google.maps.GeocoderStatus.OK) {
content.getElementsByTagName('address')[0].textContent = r[0].formatted_address;
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map-canvas"></div>
Here's how I would do it:
function reverseGeocoder(lat, lng, callback) {
var geocoder = new google.maps.Geocoder();
var point = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
geocoder.geocode({"latLng" : point }, function(data, status) {
if (status == google.maps.GeocoderStatus.OK && data[0]) {
callback(null, data[0].formatted_address);
} else {
console.log("Error: " + status);
callback(status, null);
}
});
};
And basically you would call the function like:
reverseGeocoder(lat, lng, function(err, result){
// Do whatever has to be done with result!
// EDIT: For example you can pass the result to your initialize() function like so:
initialize(result); // And then inside your initialize function process the result!
});

How to show a map focused on a marker using a click event on Google Maps JavaScript API v3?

I created a map that focuses on a user's location. The map has a single marker with an info window. When a user clicks on the info window it gives him a hyperlink to an info page (info.html). I want to create an option that will allow the user to go back from the info page to the map, and the map should be focused on the same marker (not on his current location). It's basically going the opposite way. It sounds pretty simple, but I have no idea how to code this.
I guess I can build a different map for every marker, but that seems highly unlikely to be the right solution. Any help would be appreciated.
This is my attempt with the script, (initialize2() doesn't work):
$(document).ready(function() {
getLocation();
});
var map;
var jones = new google.maps.LatLng(40.59622788325198, -73.50334167480469);
function getLocation() {
navigator.geolocation.getCurrentPosition(
function(position) {
var myLatLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(myLatLng);
},
function() {
alert("Please enable location detection on your device");
}
);
}
function initialize() {
var mapOptions = {
center: map,
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var infowindow = new google.maps.InfoWindow({
});
var marker1 = new google.maps.Marker({
position: jones,
map: map
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow.setContent('<h4>Jones Beach</h4>See info');
infowindow.open(map,marker1);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
// this is my attempt to focus on the marker
// there will be a button that will evoke this function from info.html
function initialize2() {
var mapOptions2 = {
zoom: 14,
center: new google.maps.LatLng(40.59622788325198, -73.50334167480469),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions2);
}
google.maps.event.addDomListener(window, 'load', initialize2);
What about using a hash in the url?
Try using "http://students.example.com/test.html#one":
$(function() {
var places = {
one: [40.59622788325198, -73.50334167480469],
two: [50.59622788325198, -71.50334167480469]
};
var div = $('#map-canvas');
var map = new google.maps.Map(div.get(0), {
center: map,
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var markers = {};
$.each(places, function(name) {
markers[name] = new google.maps.Marker({
position: new google.maps.LatLng(this[0], this[1]),
map: map
});
});
var place = location.hash.substr(1);
if(place in places) {
map.setCenter(markers[place].getPosition());
}
});

Adding multiple addListener events to a Google Map form with geocoding

I have created a Google Map form that lets users enter an address into a text field and geocode the entry. This then puts a marker on a map. This works fine, but I want to add an additional addListener so when the user clicks the map it will add another pin where they click. For some reason my 'click' addListener is not working. How would I have multiple add Listeners like that?
I attached my current code:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.7,-74.0),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var marker = new google.maps.Marker({
map: map,
draggable: true
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(16);
}
var image = "http://www.google.com/mapfiles/marker_green.png";
marker.setIcon(image);
marker.setPosition(place.geometry.location);
var address = '';
if (place.address_components) {
address = [(place.address_components[0] &&
place.address_components[0].short_name || ''),
(place.address_components[1] &&
place.address_components[1].short_name || ''),
(place.address_components[2] &&
place.address_components[2].short_name || '')
].join(' ');
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addListener(map, 'click', function() {
//alert("Hello! I am an alert box!!");
var marker1 = new google.maps.Marker({
map: map,
draggable: true
});
var image = "http://www.google.com/mapfiles/marker_green.png";
marker1.setIcon(image);
marker1.setPosition(new google.maps.LatLng(40.7,-74.0));
map.addOverlay(marker1);
});
</script>
The map click event will return the position of the mouse click.
Update: To erase the old marker when a new one is added you need to store an instance of the marker outside of the listener scope then you can erase it at the beginning of the listener event.
var singleMarker;
google.maps.event.addListener(map, 'click', function(event) {
//if marker exists, erase marker
if(singleMarker){
singleMarker.setMap(null);
}
singleMarker = new google.maps.Marker({
position: event.latLng, //mouse click position
map: map,
draggable: true,
icon: "http://www.google.com/mapfiles/marker_green.png"
});
});
Updated fiddle example.
You could use a
google.maps.event.addListener(map,'click', function()...
to add an onclick event to the map object. Here's a reference:
http://code.google.com/apis/maps/documentation/javascript/reference.html#Map
You could also use the Google Maps Drawing Tools library:
http://code.google.com/apis/maps/documentation/javascript/overlays.html#drawing_tools

Categories

Resources