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
Related
I am trying to locate the user and tell him nearest doctors to him but the code is showing over_query_limit. I am not able to resolve the problem as I am new to using API's
I have tried using this code but it is again showing the same problem
{% include 'includes/default.html' %}
<head>
<script type="text/javascript" src="https://www.google.com/jsapi">
</script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAVZIr_BmEFJTyl7MzSpBS_XpLrBgZEBZg&libraries=places&sensor=false"></script>
<script src="js/script.js"></script>
<!-- <script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script> -->
<!-- <script src="https://maps.googleapis.com/maps/api/js?
key=AIzaSyAVZIr_BmEFJTyl7MzSpBS_XpLrBgZEBZg&callback=initalize" -->
async defer></script>
<script type="text/javascript">
var geocoder;
var map;
var markers = Array();
var infos = Array();
function initialize() {
// prepare Geocoder
geocoder = new google.maps.Geocoder();
// set initial position (Byculla)
var myLatlng = new google.maps.LatLng(14.4426,78.9865);
var myOptions = { // default map options
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('gmap_canvas'),
myOptions);
}
// clear overlays function
function clearOverlays() {
if (markers) {
for (i in markers) {
markers[i].setMap(null);
}
markers = [];
infos = [];
}
}
// clear infos function
function clearInfos() {
if (infos) {
for (i in infos) {
if (infos[i].getMap()) {
infos[i].close();
}
}
}
}
// find address function
function findAddress() {
var address = '{{location}}';
// script uses our 'geocoder' in order to find location by address name
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) { // and, if everything
is ok
// we will center map
var addrLocation = results[0].geometry.location;
map.setCenter(addrLocation);
// store current coordinates into hidden variables
document.getElementById('lat').value =
results[0].geometry.location.lat();
document.getElementById('lng').value =
results[0].geometry.location.lng();
// and then - add new custom marker
var addrMarker = new google.maps.Marker({
position: addrLocation,
map: map,
title: results[0].formatted_address,
icon: 'marker.png'
});
} else {
alert('Geocode was not successful for the following reason: ' +
status);
}
findPlaces();
});
}
// find custom places function
function findPlaces() {
// prepare variables (filter)
var lat = document.getElementById('lat').value;
var lng = document.getElementById('lng').value;
var cur_location = new google.maps.LatLng(lat, lng);
// prepare request to Places
var request = {
location: cur_location,
radius: 2000,
types: ['hospital','doctor']
};
// send request
service = new google.maps.places.PlacesService(map);
service.search(request, createMarkers);
}
// create markers (from 'findPlaces' function)
function createMarkers(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
// if we have found something - clear map (overlays)
clearOverlays();
// and create new markers by search result
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
} else if (status == google.maps.places.PlacesServiceStatus.ZERO_RESULTS)
{
alert('Sorry, nothing is found');
}
}
// creare single marker function
function createMarker(obj) {
// prepare new Marker object
var mark = new google.maps.Marker({
position: obj.geometry.location,
map: map,
title: obj.name
});
markers.push(mark);
// prepare info window
var infowindow = new google.maps.InfoWindow({
content: '<img src="' + obj.icon + '" /><font style="color:#000;">' +
obj.name +
'<br />Rating: ' + obj.rating + '<br />Vicinity: ' + obj.vicinity + '
</font>'
});
// add event handler to current marker
google.maps.event.addListener(mark, 'click', function() {
clearInfos();
infowindow.open(map,mark);
});
infos.push(infowindow);
}
// initialization
google.maps.event.addDomListener(window, 'load', initialize);
document.getElementById("doctortab").click();
</script>
</head>
<body onload="findAddress()">
<div id="gmap_canvas" style="position: absolute; top:200px;right:20px
;height:400px;width:800px">
</div>
<input type="hidden" id="lat" name="lat" value="18.9682846" />
<input type="hidden" id="lng" name="lng" value="72.8311396" />
<!-- <input type="hidden" value="{{location}}" id="location"
name='location'> -->
</body>
The expected result is to show the user doctor but it is showing over_query_limit error
If you use Google's geolocation system, last time they made more limits to the free users. You just had to pay for higher connection limits or something like that. Anyway, you didnt posted your code.
I wrote a little html page in order to display pushpins on a map.
I give some address to my webpage, then I use the geocoding() and i display pushpins.
Then, I would like to add the google.maps.Animation.DROP with a timeout like explained on the Google Maps API page. ( https://developers.google.com/maps/documentation/javascript/examples/marker-animations-iteration?hl=fr)
On the Google Maps API page, the sample code directly uses the coordinates. It's simple.
In my case, I need to use before the geocoding() to get points, then display the pushpins.
I really don't understand but I'm unable to use this Drop animation with timeout using geocoding. I used the debugger view in Chrome, and I don't understand.
Here is my code, i tried to do as simple as possible :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
width:100%;
height:100%;
}
</style>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps</title>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAs4c8xnkxcZNRK6yQt-Y21N1L3mT1AFfE&callback=initMap">
</script>
</head>
<body>
<div id="map" ></div>
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
<script type="text/javascript">
//<![CDATA[
var infoWindow;
var map;
var geocoder;
var bounds;
var TbCoordonnees = [];
var TbMarkers = [];
var AdresseTiersTb = [];
function initMap()
{
geocoder = new google.maps.Geocoder();
var optionsCarte = {
zoom: 8,
center: new google.maps.LatLng(48.5, 2.9),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), optionsCarte);
bounds = new google.maps.LatLngBounds();
infoWindow = new google.maps.InfoWindow({});
// EXAMPLE :
AdresseTiersTb.push("39 Boulevard de Courtais, 03100 Montluçon");
AdresseTiersTb.push("Place de l'Hôtel de ville, 13100 Aix-en-Provence");
AdresseTiersTb.push("55 Rue du Faubourg Saint-Honoré, 75008 Paris");
AdresseTiersTb.push("Place des Buisses, 59000 Lille");
for (var i = 0; i < AdresseTiersTb.length; i++)
{
geocodeAddress(AdresseTiersTb[i],i*200);
}
}
function geocodeAddress(address,timeout)
{
geocoder.geocode(
{'address': address},
function(results, status)
{
if((results != null) && (status == google.maps.GeocoderStatus.OK))
{
var marker = createMarker(address,timeout,results);
}
else
{
alert("geocode failed on "+address+", status="+status);
}
}
);
}
function createMarker(address,timeout,results)
{
var marker;
window.setTimeout(function() {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,animation: google.maps.Animation.DROP
});},timeout);
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds)
map.panToBounds(bounds);
map.setCenter(bounds.getCenter());
var infocontent = address;
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(infocontent);
infoWindow.open(map, marker);
});
return marker;
}
function listenMarker (marker, info)
{
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(info);
infoWindow.open(map, this);
});
}
</script>
The problem is the var marker appear to be undefined, so no pushpins once pushpin is displayed instead of three. I don't know why but when I look in debug mode I don't understand how the geocoding is executed. Very strange.
You can't return a useful value of the marker variable from the asynchronous setTimeout callback function (where it is created and added to the map). The function returns the variable immediately (before it is defined by the callback of the setTimeout call (which runs some time later). The marker is also not defined when you are adding the click event listener.
proof of concept fiddle
code snippet:
var infoWindow;
var map;
var geocoder;
var bounds;
var TbCoordonnees = [];
var TbMarkers = [];
var AdresseTiersTb = [];
function initMap() {
geocoder = new google.maps.Geocoder();
var optionsCarte = {
zoom: 8,
center: new google.maps.LatLng(48.5, 2.9),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), optionsCarte);
bounds = new google.maps.LatLngBounds();
infoWindow = new google.maps.InfoWindow({});
// EXAMPLE :
AdresseTiersTb.push("Versailles, FR");
AdresseTiersTb.push("Paris, FR");
AdresseTiersTb.push("Sens, FR");
for (var i = 0; i < AdresseTiersTb.length; i++) {
geocodeAddress(AdresseTiersTb[i], i * 200);
}
}
function geocodeAddress(address, timeout) {
// function closure on address.
geocoder.geocode({
'address': address
},
function(results, status) {
if ((results != null) && (status == google.maps.GeocoderStatus.OK)) {
createMarker(address, results[0].geometry.location, timeout);
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds)
} else {
alert("geocode failed on " + address + ", status=" + status);
}
}
);
}
function createMarker(address, latLng, timeout) {
// function closure on address, latLng
window.setTimeout(function() {
var marker = new google.maps.Marker({
map: map,
position: latLng,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', (function(marker, address) {
// function closure on marker, address
return function() {
infoWindow.setContent(address);
infoWindow.open(map, marker);
}
})(marker, address));
}, timeout);
}
function listenMarker(marker, info) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(info);
infoWindow.open(map, this);
});
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
I want to change Alert message(alert('Geocode was not successful for the following reason: ' + status);) to be displayed in the div on Google Map Geocoding service search. What is the best way to do this?
https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
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);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
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
});
// Remove Div if Error message exist on the page
var elem = document.getElementById("lsError");
if (elem) {
elem.parentNode.removeChild(elem);
}
} else {
//alert('Geocode was not successful for the following reason: ' + status);
// Add error message in the div id=lsError
if (!document.getElementById("lsError")) {
var node = document.createElement("div");
node.id = "lsError";
var textnode = document.createTextNode("Please Enter Zipcode or City");
node.appendChild(textnode);
document.getElementById("searchLocation").appendChild(node);
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
with CSS for error message.
<style>
#searchLocation{
position: relative;
}
#lsError{
position: absolute;
bottom: -20px;
background: red;
color: #fff;
padding: 10px;
}
</style>
So I ended up using Javascript to create error message in Div. Seems like it works.
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';
I've heard that it is possible to submit an Address instead of Longitude and Latitude and this would be much more feasible for my system. The user has to input their address when creating their profile and their profile afterwards will then display a Google Maps of their house. I currently have the Google Maps API working perfectly with Longitude and Latitude:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="css.css" />
<title>Login Page</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=MYKEY&sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.640143,1.28685),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(52.640143,1.28685),
map: map,
title: "Mark On Map"
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
Please could somebody assist me to alter my code so that it enables the Google Maps API to request an Address in its place because I want to read the Address of the user directly from mySQL database.
See this example, initializes the map to "San Diego, CA".
Uses the Google Maps Javascript API v3 Geocoder to translate the address into coordinates that can be displayed on the map.
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Geocoding Simple</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
var address ="San Diego, CA";
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
if (geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow(
{ content: '<b>'+address+'</b>',
size: new google.maps.Size(150,50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title:address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="initialize()">
<div id="map_canvas" style="width:100%; height:100%">
</body>
</html>
working code snippet:
var geocoder;
var map;
var address = "San Diego, CA";
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
if (geocoder) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.setCenter(results[0].geometry.location);
var infowindow = new google.maps.InfoWindow({
content: '<b>' + address + '</b>',
size: new google.maps.Size(150, 50)
});
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title: address
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
}
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" ></div>
You can parse the geolocation through the addresses.
Create an Array with jquery like this:
//follow this structure
var addressesArray = [
'Address Str.No, Postal Area/city'
]
//loop all the addresses and call a marker for each one
for (var x = 0; x < addressesArray.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addressesArray[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
//it will place marker based on the addresses, which they will be translated as geolocations.
var aMarker= new google.maps.Marker({
position: latlng,
map: map
});
});
}
Also please note that Google limit your results if you don't have a business account with them, and you my get an error if you use too many addresses.
Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map.
Would this be what you are looking for: Contains sample code
https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingRequests
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'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == '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);
}
});
}
<body onload="initialize()">
<div id="map" style="width: 320px; height: 480px;"></div>
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Encode" onclick="codeAddress()">
</div>
</body>
Or refer to the documentation https://developers.google.com/maps/documentation/javascript/geocoding
Thought I'd share this code snippet that I've used before, this adds multiple addresses via Geocode and adds these addresses as Markers...
var addressesArray = [
'Address Str.No, Postal Area/city',
//follow this structure
]
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 12.7826,
lng: 105.0282
},
zoom: 6,
gestureHandling: 'cooperative'
});
var geocoder = new google.maps.Geocoder();
for (i = 0; i < addressArray.length; i++) {
var address = addressArray[i];
geocoder.geocode({
'address': address
}, function(results, status) {
if (status === 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
center: {
lat: 12.7826,
lng: 105.0282
},
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}