Using http://ubilabs.github.com/geocomplete/examples/draggable.html as an example.
jQuery("#geocomplete").bind("geocode:dragged", function(event, latLng){
jQuery("input[name=lat]").val(latLng.lat());
jQuery("input[name=lng]").val(latLng.lng());
});
I am able to get the marker position in form of lat lng after the marker is dragged. But I am not able to get current location of the marker after being dragged.
I want to update my location text box on the current position of marker after being dragged.
I managed to find a better work around!
The work around you that Nadeeshani posted isn't very precise and it centres the map to a nearest address.
I managed to fix this by using the google geocoded, test the following code.
var options = {
map: "#mapnew",
country: 'uk',
mapOptions: {
streetViewControl: false,
mapTypeId : google.maps.MapTypeId.HYBRID
},
markerOptions: {
draggable: true
}
};
$("#address").geocomplete(options).bind("geocode:result", function(event, result){
$('#logs').html(result.formatted_address);
var map = $("#address").geocomplete("map");
map.setZoom(18);
map.setCenter(result.geometry.location);
});
$("#address").bind("geocode:dragged", function(event, latLng){
console.log('Dragged Lat: '+latLng.lat());
console.log('Dragged Lng: '+latLng.lng());
var map = $("#address").geocomplete("map");
map.panTo(latLng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latLng }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var road = results[0].address_components[1].long_name;
var town = results[0].address_components[2].long_name;
var county = results[0].address_components[3].long_name;
var country = results[0].address_components[4].long_name;
$('#logs').html(road+' '+town+' '+county+' '+country);
}
}
});
});
See my JSFiddle Example
This may not be a 100% perfect solution, but I too had the same issue and this is how I got through it. This is kind of a workaround.
$("#geocomplete").bind("geocode:dragged", function(event, latLng){
$("input[name=lat]").val(latLng.lat());
$("input[name=lng]").val(latLng.lng());
$("#geocomplete").geocomplete("find", latLng.toString());
});
The only problem here is the map is setting to its default zomm size since the autocomplete is sort of re initializing here.
Hope this will help
I am not sure if this is the same issue, but my 'find' also returned the incorrect result when doing more then one 'find'. It seems it is because the 'bounds' are set on subsequent finds, and the wrong results are return.
As a workaround, I changed the "jquery.geocomplete.js" file as follow, by adding this line:
request.bounds = this.options.bounds;
just before this line (352):
this.geocoder.geocode(request, $.proxy(this.handleGeocode, this));
then the find should work as per normal:
$("#geocomplete").geocomplete("find", latLng.toString());
Related
I'm trying to create a transit map (with bus/metro indications) using Google Maps, but when I create the "start" and "end" markers from inputs (with autocomplete addresses), there's no way to drag any marker despite set drag option as true.
Changing the travelMode option to google.maps.TravelMode.DRIVING the draggin' is enabled. And going back this property to google.maps.TravelMode.TRANSIT the daggin' goes back to disabled.
There's a way to solve this issue?
Code:
var directionsService;
var directionsDisplay;
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: {lat: -32.89, lng: -68.845} // Mendoza.
});
directionsService = new google.maps.DirectionsService;
directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
panel: document.getElementById('right-panel')
});
directionsDisplay.addListener('directions_changed', function() {
var addresses = directionsDisplay.getDirections().routes[0].legs[0];
document.getElementById('from').value = addresses.start_address;
document.getElementById('to').value = addresses.end_address;
});
google.maps.event.addDomListener(document.getElementById('go'), 'click', displayRoute);
var input_from = document.getElementById('from');
var autocomplete = new google.maps.places.Autocomplete(input_from);
autocomplete.bindTo('bounds', map);
var input_to = document.getElementById('to');
var autocomplete = new google.maps.places.Autocomplete(input_to);
autocomplete.bindTo('bounds', map);
displayRoute();
}
function displayRoute() {
directionsService.route({
origin: document.getElementById('from').value,
destination: document.getElementById('to').value,
//travelMode: google.maps.TravelMode.DRIVING,
travelMode: google.maps.TravelMode.TRANSIT
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
console.log(response);
directionsDisplay.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initMap);
Unfortunately, the "draggable" mode is not permited to the TRANSIT travel mode. Just now I'm trying to find a way and I found your question by the way.
EDIT
As the google documentation says:
Users may modify cycling, walking or driving directions displayed
using a DirectionsRenderer dynamically if they are draggable, allowing
a user to select and alter routes by clicking and dragging the
resulting paths on the map. You indicate whether a renderer's display
allows draggable directions by setting its draggable property to true.
Transit directions cannot be made draggable.
Check it here: https://developers.google.com/maps/documentation/javascript/directions#TransitOptions
We will have to find another way... if I find it I'll make you know, if you find it first I'll be grateful if you told me.
The "solution" (hack) I found, using trial and error, is to prevent to show the markers the API creates:
var directionsDisplay = new m.DirectionsRenderer({
suppressMarkers: true, // Supressing the default markers
map: map,
// another options...
});
And implement my own function to show markers:
function placeMarker(e, t) {
t < 2 && (markers[t] = new m.Marker({
position: e,
draggable: true, // YES! It's draggable!
map: map
}), m.event.addListener(markers[t], "dragend", function() {
geocodePosition(markers[t].getPosition(), t);
}), markers[t].setVisible(true), geocodePosition(markers[t].getPosition(), t), arrangeBounds());
}
Then, the markers are draggable using a Google transit map... The solution is late but, I hope, not least.
This is my first post and I hope I can get some help since I am relatively new to the development arena, please excuse me if my questions are a bit stupid.
I am trying to make sort of a dashboard implementing a dependency from a drop down list in html - let's say that based on the drop down list value selected, a div tag containing a google maps reference should be updated.
For example:
I choose a continent from the drop down list, and then Google will shift its view on that area, later on showing customized points of interest on the map. Can someone help me or suggest a possible solution?
Thank you!
Make sure to include the Google Maps Javascript API (I assume you've already done this):
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
JS:
var map;
var geocoder;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 10,
streetViewControl: false
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
geocoder = new google.maps.Geocoder();
}
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function() {
$('input.maps-input').on('change', function() {
geocoder.geocode({ 'address': $(this).val()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
map.setCenter(results[0].geometry.location);
else
alert('A location could not be found. ' + status);
});
});
});
Then add a dropdown (or any type of input) with class maps-input to your page and a div with class map-canvas (of course you can change these class names to whatever you want).
This question might be answered in other posts, but I haven't found the specific answer and I'm having trouble discerning how to logically think through this. I have a site where each post has an address. On each post page I've used the Google Maps API to translate the address into a map location and to show a map with a pin at that address. Works great.
What I need to do now is to show a map at the top of my archive/category/etc pages (pages with a list of posts generated by a query and a loop) and to list a pin for every post that shows up in that particular query. I also need the map to automatically resize to show all of the pins, and not show extraneous map outside of the pins boundaries.
The way it seems that this would happen is that I could create the markers with a script that's inside the loop, so that each time the loop runs, it would generate a new marker and add it to the map.
Another possible method that seems like it has potential would be to add the location to an array for each turn of the loop, and then show the array of pins when the loop is done.
Can anyone give me some advice on how to accomplish this? At this point I'm using the following code which gives me a map and the location of the last post in the list generated by the loop. This code is outside of the loop. I need to know which part I should move inside the loop, and how to adjust it so that I won't simply rewrite the marker during every iteration of the loop.
<script type="text/javascript">
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 3,
}
var myAddress = document.getElementById('theAddress');
var address = myAddress.textContent;
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,
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You need to add markers in a loop. this was taken from a project i was working.
var locations = ["Denver, CO, United States"];
var markers = [];
var iterator = 0;
for (var i = 0; i < locations.length; i++) {
setTimeout(function() {
geocoder.geocode({'address': locations[iterator]}, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
animation: google.maps.Animation.DROP
});
bounds.extend(marker.getPosition());
map.fitBounds(bounds);
} else {
log('Geocode was not successful for the following reason: ' + status);
}
});
iterator++;
}, i * 250);
}
On the contact page of my site two things can happen:
The user has geolocation enabled, and a map (map-canvas) will display a route from their location to a predefined location dest. This feature works fine.
The user doesn't have geolocation enabled or chooses not to allow it. An alert will show (works fine), and some text will be added to the directions-panel (works fine). The third thing I want to happen in this scenario is a new map be added to map-canvas that is centred on dest, this feature doesn't seem to be working and I can't figure out why.
Code below should give a good representation of the above:
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var dest = "Unit 20, Tallaght Business Centre, Whitestown Road, Tallaght Business Park, Ireland";//53.282882, -6.383155
var ourLocation = {lat : 53.282882, lng : -6.383155}//centre attribute of the map must be a LatLng object and not hardcoded as above
function initGeolocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition( success, failure );
}
}
//create a new map centered on user's location, display route and show directions
function success(position) {
directionsDisplay = new google.maps.DirectionsRenderer();
coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directions-panel"));
calcRoute();
}
//calculate the route from user's location to 'dest'
function calcRoute() {
var start = coords;
var end = dest;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
//tell user geoloc isn't enabled and just plot 'ourLocation' on 'map-canvas'
function failure() {
alert("Your browser does not have geolocation enabled so we can't give you directions to our office. Enable geolocation and try again, or consult the map for our address.");
$("#directions-error-message").css({
visibility: 'visible'
});
var destMapOptions = {
zoom:13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(ourLocation.lat, ourLocation.lng)
}
map = new google.maps.Map(document.getElementById("map-canvas"), destMapOptions);
}
</script>
Anyone have any ideas why this isn't working? All help appreaciated.
EDIT: Working version above
You need to pass the map a LatLng object for it's centre, not an address. You will need to use Googles LocalSearch services to make that work.
var dest = {
lat : 53.282882,
lng : -6.383155
}
var destMapOptions = {
zoom:12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(dest.lat,dest.lng)
}
Also, as you have map declared as a var already maybe use that rather than a function scoped variable for the map.
The center attribute of the map options must be a LatLng object. You've got it hardcoded as an address string.
I can't zoom to a marker properly.
I'm trying to switch the view to a specified marker, but can't ge tit to work.
I've tried
map.setCenter(location);
map.setZoom(20);
and
map.fitBounds(new google.maps.latLngBounds(location,location));
but in the first case, I simply get zoomed in without the center change being registered, and in the second case I get this overview over a huge area, not zoomed in at all.
Perhaps this issue could be solved by setting a timout from setcenter to setzoom, but that's an ugly hack to me, so a prettier solution would be preferred.
How do you guys do this?
Also - if the infowindow could be displayed without changing content, that would really be a plus to, but the most important thing is to zoom into the marker at the right spot, close up.
thank you very much.
The solution turned out to be
map.setZoom(17);
map.panTo(curmarker.position);
I thought I would post an answer here as people wanted some example code.
I too needed to be able to zoom in and center as soon as a marker was added to the map.
Hope this helps somebody.
function getPoint(postcode) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': postcode + ', UK'}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
map.setZoom(10);
map.panTo(marker.position);
}
else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
is this a new instance of a map object you are creating? if so you can just have an object which contains the location and zoom and then pass that object to the map when initalising it like so (taken from the Gmaps basics tutorial http://code.google.com/apis/maps/documentation/javascript/basics.html:
function initialize() {
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}