Center Google Maps to location string [duplicate] - javascript

This question already has answers here:
Using Address Instead Of Longitude And Latitude With Google Maps API
(5 answers)
Closed 8 years ago.
Using Google Maps API, I would like to center the map to a string instead of Lat/Lng
var mapOptions = {
center: "Paris"
};

You can use the geocoder.
Working code snippet:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(0, 0);
var mapOptions = {
zoom: 8,
center: latlng
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// Call the codeAddress function (once) when the map is idle (ready)
google.maps.event.addListenerOnce(map, 'idle', codeAddress);
}
function codeAddress() {
// Define address to center map to
var address = 'Paris, France';
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// Center map on location
map.setCenter(results[0].geometry.location);
// Add marker on 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);
}
});
}
initialize();
#map-canvas {
height: 180px;
}
<div id="map-canvas"></div>
<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
JSFiddle demo
Edit: of course you can geocode a complete address like this:
// Define address to center map to
var address = 'Rue Casse-Cul, Montboucher-sur-Jabron, France';

Related

Google Maps JavaScript API v3 drawing line between two location [duplicate]

This question already has an answer here:
How to connect two points in Google map..?
(1 answer)
Closed 8 years ago.
please help me on this, I really stuck on this!
my code is:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Geocoding service</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
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 marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
var address2 = document.getElementById('address2').value;
geocoder.geocode( { 'address2': address2}, function(results2, status2) {
if (status2 == google.maps.GeocoderStatus.OK) {
var marker2 = new google.maps.Marker({
map: map,
position: results2[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
var myTrip = [address,address2];
var flightPath = new google.maps.Polyline({
path:myTrip,
strokeColor:"#00F",
strokeOpacity:0.8,
strokeWeight:2
});
flightPath.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<input id="address" type="textbox" value="address 1">
<input id="address2" type="textbox" value="address 2">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas"></div>
</body>
</html>
I want to enter two address in the input, convert it to lat/long separately, put two markers on the map and draw a straight line between them!
my code is not working, it's displaying only the first address and that's all...
thank you in advance!
Well, it seems that you had at least syntax error (address2) because you defined:
geocoder.geocode( { 'address2': address2}, function(results2, status2) {
instead of:
geocoder.geocode( { 'address': address2}, function(results2, status2) {
However, you also had errors when defining the actual polyline, because geocoding is asynchronous you cant call creation of the polyline after geocode lines, instead you need to make separate method or similar callback functionality which is called when geocoding finishes. Otherwise, you are just handling undefined values.
Therefore, I decided to add method called displayMarkers() which is called from each geocode request which in turn checks whether all addresses is geocoded and acts accordingly. Here is the code with the changes: (It also works without page refresh, you can try seaching multiple addresses in a row).
var geocoder;
var map;
var geocodeMarkers = [];
var flightPath;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
// Emptying last addresses because of recent query
for(var i = 0; i < geocodeMarkers.length; i++) {
geocodeMarkers[i].setMap(null);
}
// Empty array
geocodeMarkers.length = 0;
// Empty flight route
if(typeof flightPath !== "undefined") {
flightPath.setMap(null);
flightPath = undefined;
}
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// Adding marker to geocodeMarkers
geocodeMarkers.push(
new google.maps.Marker({
position: results[0].geometry.location
})
);
// Attempting to display
displayMarkers();
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
var address2 = document.getElementById('address2').value;
geocoder.geocode( { 'address': address2 }, function(results2, status2) {
if (status2 == google.maps.GeocoderStatus.OK) {
// Adding marker to geocodeMarkers
geocodeMarkers.push(
new google.maps.Marker({
position: results2[0].geometry.location
})
);
// Attempting to display
displayMarkers();
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function displayMarkers() {
// If geocoded successfully for both addresses
if(geocodeMarkers.length === 2) {
// Bounds for the markers so map can be placed properly
var bounds = new google.maps.LatLngBounds(
geocodeMarkers[0].getPosition(),
geocodeMarkers[1].getPosition()
);
// Fit map to bounds
map.fitBounds(bounds);
// Setting markers to map
geocodeMarkers[0].setMap(map);
geocodeMarkers[1].setMap(map);
flightPath = new google.maps.Polyline({
path: [geocodeMarkers[0].getPosition(), geocodeMarkers[1].getPosition()],
strokeColor:"#00F",
strokeOpacity:0.8,
strokeWeight:2,
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
Working jsfiddle example: js fiddle demonstration 1
Edit:
After further comments, author of this topic wanted to center map on first geocoded marker. It is accomplished by changing following lines:
// Bounds for the markers so map can be placed properly
var bounds = new google.maps.LatLngBounds(
geocodeMarkers[0].getPosition(),
geocodeMarkers[1].getPosition()
);
// Fit map to bounds
map.fitBounds(bounds);
To:
// Center map to first geocoded location
map.setCenter(geocodeMarkers[0].getPosition());
Working jsfiddle for this: js fiddle demonstration 2

retrieve latitude and longitude in google map [duplicate]

This question already has an answer here:
How do I return a longitude and latitude from Google Maps JavaScript geocoder? [duplicate]
(1 answer)
Closed 9 years ago.
I can setup a pushpin on map but i am not able to retrieve the latitude and longitude of that point. Here is my code. Can anyone help with this?
Thanks
function codeaddress() {
var geocoder;
//map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
geocoder = new google.maps.Geocoder();
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 marker = new google.maps.Marker({
animation: google.maps.Animation.BOUNCE,
flat: false,
map: map,
position: results[0].geometry.location
});
var latt = document.getElementById("latitude");
latt.value = results[0].geometry.location.getlatitude();
alert(latt.value);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
try using .lat() instead of .getLatitude().
see the API about the LatLng class: https://developers.google.com/maps/documentation/javascript/reference#LatLng

Google Maps Apiv3 - Geocode function to get latitude longtitude not working

I modified the javascript from https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-simple to
var geocoder;
var postalArr = [];
postalArr.push(249586);
postalArr.push(266751);
var map;
function initialize(){
var myLatlng = new google.maps.LatLng(1.3667, 103.7500);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
if (postalArr) {
for (var i = 0; i < postalArr.length; i++ ) {
codeAddress(postalArr[i]);
}
}
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
}
function codeAddress(postal) {
geocoder.geocode( { 'postal': postal}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var markerE = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
The script goes within the for loop but doesn't run the codeAddress function.
I'm not sure why.
Two things.
(1) need to define geocoder somewhere, I put it in the initialize
function initialize(){
geocoder = new google.maps.Geocoder();
(2) there's no such thing as a postal property to feed the geocoder. Valid requests are for a latlng or an address as explained here.
So at least you must specify a country. I'm not sure what country 249586 is for, in my demo I used two California zip codes, and added ", United States" to the address.
geocoder.geocode( { 'address': postal + ", United States"},

Google maps placemark doesn't replace old placemark

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);
}
});
}

Google Maps v3 - How to center using an address on initialize?

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

Categories

Resources