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));
Related
i am trying to get address using reverse geocoding.
but there is some problem in geocoder.geocode({...}) line. even normal alert message also not display.
function initialize() {
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
var input=e.latLng;
var lat = parseFloat(input.lat());
var lng = parseFloat(input.lng());
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(results[1].formatted_address);
}
});
});
}
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
google.maps.event.addDomListener(window, 'load', initialize);
add below line inside initialize() function.
var geocoder = new google.maps.Geocoder();
Hi i'm wanting to create a map that, when a function is called, generates directions to a point based on the users current geolocation. I have tried to do this and so far my attepts have been fruitless, here is my current JS code:
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var start = latlon;
var end = "Darwin, NSW, Australia";
var request =
{
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVIN
};
function initialize()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position)
{
directionsDisplay = new google.maps.DirectionsRenderer();
var latlon = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions =
{
zoom:15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlon
}
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
}
}
function getdirections()
{
directionsService.route(request, function(response, status)
{
if (status == google.maps.DirectionsStatus.OK)
{
directionsDisplay.setDirections(response);
}
});
}
Any Help would be greatly appreciated, but keep in mind it must use the google maps api, v3. Thank you :)
Please checkout this jsfiddle,
Here i have hard-coded the starting position and end position is the users current position.
Is this what you are looking for ?
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);
}
});
}
I'm trying to accomplish the following with the Google Maps API:
Display to_address as a marker on the map
Get users location
Generate and display directions based on the information given by gps/user input
I have gotten the last two to work just fine. The problem I am having now is showing the to_address as a marker on the map if the location is not provided.
This is the code I am using. Keep in mind the last 2 steps work as expected. I know that I can accomplish this using latlng but that is not an option for me. I need to provide it an address.
var geocoder;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var to_pos;
var to_address = '11161 84th ave delta bc';
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': to_address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
to_pos = results[0].geometry.location;
}
});
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: to_pos
};
var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions'));
var control = document.getElementById('d_options');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var infowindow = new google.maps.Marker({
position: pos,
map: map,
title: "You"
});
map.setCenter(pos);
$('#from').val(pos);
$('#d_options').trigger('collapse');
calcRoute();
}, function () {
handleNoGeolocation(true);
});
}
}
function calcRoute() {
var start = document.getElementById('from').value;
var end = to_address;
$('#results').show();
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);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
geocoding uses an asynchronous request. You must create the marker inside the callback of geocode()
geocoder.geocode({
'address': to_address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var to_pos = results[0].geometry.location;
new google.maps.Marker({
position: new google.maps.LatLng(to_pos.lat(),to_pos.lng()),
map: map,
title: "Destination"
});
}
});
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