I'm using the Google Maps JavaScript API to display routes and text directions:
JS:
var geocoder;
var map;
var search_lat;
var search_lng;
function initMap() {
var myLatLng = {
lat: 38.5803844,
lng: -121.50024189999999
};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: myLatLng,
});
geocoder = new google.maps.Geocoder();
document.getElementById('search_button').addEventListener('click', function() {
getDirectionsByAddress(geocoder, map);
});
var locations = <?php echo json_encode($locations_array); ?>;
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][5], locations[i][6]),
animation: google.maps.Animation.DROP,
icon: icon_image,
map: map
});
}
}
function getDirectionsByAddress() {
// GET THE SEARCH ADDRESS
var address = document.getElementById('address').value;
console.log('search address: ' + address);
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
search_lat = results[0].geometry.location.lat();
search_lng = results[0].geometry.location.lng();
console.log('search address coordinates: ' + search_lat + ', ' + search_lng);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
// INITIALIZE GOOGLE MAPS DIRECTIONS SERVICE
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions'));
calculateAndDisplayRoute(directionsService, directionsDisplay);
// CHECK THE MODE OF TRAVEL
document.getElementById('mode').addEventListener('change', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
// CALCULATE THE DIRECTIONS BASED ON ADDRESS ENTERED AND MODE OF TRAVEL
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
console.log('search address coordinates: ' + search_lat + ', ' + search_lng);
var selectedMode = document.getElementById('mode').value;
directionsService.route({
origin: {lat: search_lat, lng: search_lng},
destination: {lat: 38.5803844, lng: -121.50024189999999},
travelMode: google.maps.TravelMode[selectedMode]
}, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
}
I'm having trouble with the getDirectionsByAddress function. When I search a location and click the "search button" the first time, nothing happens. On the second click of the "search button", the route is drawn successfully on the map and the directions are displayed, however the directions are displayed twice (it seems the directions were calculated on the first click, but only on the second click are they being displayed). If I search a third time, the third set of directions are tacked on and this repeats over and over.
It seems I need to reset the lat and lng values during each search. I tried:
delete search_lat;
delete search_lng;
inside and at the end of the calculateAndDisplayRoute function. No luck.
HTML:
<div id="map"></div>
<div id="directions">
<h3>Directions</h3>
</div>
<div class="search_block">
<input type="text" name="address" id="address" class="address" placeholder="Where are you coming from?" />
</div>
<div class="search_block">
<select name="travel_mode" id="mode">
<option>DRIVING</option>
<option>WALKING</option>
<option>BICYCLE</option>
<option>TRANSIT</option>
</select>
</div>
<div class="search_block">
<button id="search_button" onclick="getDirectionsByAddress();">Search</button>
</div>
Question: How can I make it so the directions are refreshed with a single set of coordinates during each search?
search_lat and search_lng are null until the geocoder returns results.
the geocoder is asynchronous, its results don't come back until after you place the first call to the directions service.
a hint is this error in the javascript console: Uncaught TypeError: Cannot read property 'b' of null
Move the call to the directions service into the callback function for the geocoder (where/when the data exists).
Fix that, and create a single instance of the DirectionsRenderer and it works for me.
proof of concept fiddle
code snippet:
google.maps.event.addDomListener(window, "load", initMap);
var geocoder;
var map;
var search_lat;
var search_lng;
var directionsDisplay;
var directionsService;
function initMap() {
var myLatLng = {
lat: 38.5803844,
lng: -121.50024189999999
};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: myLatLng,
});
directionsDisplay = new google.maps.DirectionsRenderer;
directionsService = new google.maps.DirectionsService;
geocoder = new google.maps.Geocoder();
document.getElementById('search_button').addEventListener('click', function() {
getDirectionsByAddress(geocoder, map);
});
var locations = []; //<?php echo json_encode($locations_array); ?>;
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][5], locations[i][6]),
animation: google.maps.Animation.DROP,
icon: icon_image,
map: map
});
}
}
function getDirectionsByAddress() {
// GET THE SEARCH ADDRESS
var address = document.getElementById('address').value;
console.log('search address: ' + address);
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
search_lat = results[0].geometry.location.lat();
search_lng = results[0].geometry.location.lng();
console.log('search address coordinates: ' + search_lat + ', ' + search_lng);
calculateAndDisplayRoute(directionsService, directionsDisplay);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
// INITIALIZE GOOGLE MAPS DIRECTIONS SERVICE
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions'));
// CHECK THE MODE OF TRAVEL
document.getElementById('mode').addEventListener('change', function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
});
// CALCULATE THE DIRECTIONS BASED ON ADDRESS ENTERED AND MODE OF TRAVEL
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
console.log('search address coordinates: ' + search_lat + ', ' + search_lng);
var selectedMode = document.getElementById('mode').value;
directionsService.route({
origin: {
lat: search_lat,
lng: search_lng
},
destination: {
lat: 38.5803844,
lng: -121.50024189999999
},
travelMode: google.maps.TravelMode[selectedMode]
}, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="directions">
<h3>Directions</h3>
</div>
<div class="search_block">
<input type="text" name="address" id="address" class="address" placeholder="Where are you coming from?" value="San Franscisco, CA" />
</div>
<div class="search_block">
<select name="travel_mode" id="mode">
<option>DRIVING</option>
<option>WALKING</option>
<option>BICYCLE</option>
<option>TRANSIT</option>
</select>
</div>
<div class="search_block">
<button id="search_button" onclick="getDirectionsByAddress();">Search</button>
</div>
<div id="map"></div>
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 have an application which displays postcodes from a database, when a button is clicked the postcodes are geocoded and displayed as markers on a Google map in a pop up window. I'm trying to show the driving route between the two markers on the map. I have saved the geocoded values into HTML span tags and I'm trying to use these values as the origin and destination for the route. Everything works apart from the route showing between the markers which shows an error message 'Directions request failed due to NOT_FOUND'.
Any idea how I can get the route to show up?
$(document).ready(function () {
$(".openMap").click(function () {
var directionsService = new google.maps.DirectionsService;
var mapLocation = $(this).prev().prev().prev().text();
var secondMarker = $(this).prev().prev().text();
window.markers = [];
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: mapLocation }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mapOptions = { center: results[0].geometry.location, zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP };
map = new google.maps.Map(document.getElementById('map'), mapOptions);
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
directionsDisplay.setMap(map);
var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: "Departure Location" });
markers.push(marker);
$('#route1').text(results[0].geometry.location);
}
});
var geocoder2 = new google.maps.Geocoder();
geocoder.geocode({ address: secondMarker }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker2 = new google.maps.Marker({ map: map, position: results[0].geometry.location, title: "Destination Location" });
markers.push(marker2);
$('#route2').text(results[0].geometry.location);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
});
directionsService.route({
origin: $('#route1').text(),
destination: $('#route2').text(),
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
$("#map").dialog({ title: "Lift Location ", height: 500, width: 500, modal: true });
});
});
route1 and route2 are empty. The API doesn't know how to create a route from "" to "".
Once I fix that (to use post1 and post2 which contain the postcodes), I get a javascript error: Uncaught ReferenceError: directionsDisplay is not defined.
Fixing that shows me a route.
proof of concept fiddle
code snippet:
$(document).ready(function() {
var directionsDisplay;
$(".openMap").click(function() {
var directionsService = new google.maps.DirectionsService;
var mapLocation = $(this).prev().prev().prev().text();
var secondMarker = $(this).prev().prev().text();
window.markers = [];
var geocoder = new google.maps.Geocoder();
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
geocoder.geocode({
address: mapLocation
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
directionsDisplay.setMap(map);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: "Departure Location"
});
markers.push(marker);
$('#route1').text(results[0].geometry.location);
}
});
var geocoder2 = new google.maps.Geocoder();
geocoder.geocode({
address: secondMarker
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker2 = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: "Destination Location"
});
markers.push(marker2);
$('#route2').text(results[0].geometry.location);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
});
console.log("post1:" + $('.post1').text());
console.log("post2:" + $('.post2').text());
directionsService.route({
origin: $('.post1').text(),
destination: $('.post2').text(),
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
if (!directionsDisplay || !directionsDisplay.getMap || (directionsDisplay.getMap() == null)) {
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
directionsDisplay.setMap(map);
}
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
$("#map").dialog({
title: "Lift Location ",
height: 500,
width: 500,
modal: true
});
$(".selector").dialog({
resizeStop: function(event, ui) {
google.maps.event.trigger(map, 'resize');
}
});
$(".selector").dialog({
open: function(event, ui) {
google.maps.event.trigger(map, 'resize');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://maps.google.com/maps/api/js"></script>
<div id="map" style="display: none;">
</div>
<span class='post1'>G1 3SL</span>
<span class='post2'>G1 2AF</span>
<br/>
<button class='openMap'>View On Map</button>
<br/>
<span id="route1"></span>
<span id="route2"></span>
I want to gather information as I click on the map in JavaScript. I'm using Google Maps API. As I right click on the map a reverse Geocode tool works and gets the information of the point clicked.
What I want to do is as I clicked on the map I want to see these Geocoded points names and some attributes in a list.
Is it even possible ?
here I'm sharing some of my code ;
This is clicking and getting coordinates ;
google.maps.event.addListener(map, "rightclick", function (event) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
alert(markersinfo);
document.getElementById("latlng").value = lat.toFixed(5) + ', ' + lng.toFixed(5);
geocodeLatLng(geocoder, map, infowindow);
});
Here is geocoding ;
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
//map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
markersinfo.push(marker);
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
I've tried to create an array called markersinfo[] and tried to push markers in to this array but I've realized that I'm just sending objects to array but not the informations. I need Geocode string , latitude and longitude of each clicked point in this markersinfo[] array.
So, instead of google.maps.Marker objects you would like to save lat, lng and address properties in markersinfo array, right? If so, the below example shows how to accomplish it:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {
lat: -28.643387,
lng: 153.612224
},
mapTypeControl: true
});
var infowindow = new google.maps.InfoWindow({
content: ''
});
var geocoder = new google.maps.Geocoder();
var markersinfo = [];
google.maps.event.addListener(map, "rightclick", function(event) {
geocodeLatLng(geocoder, event.latLng,
function(results) {
if (results[0]) {
var marker = new google.maps.Marker({
position: event.latLng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
markersinfo.push({
'address': results[0].formatted_address,
'lat': event.latLng.lat(),
'lng': event.latLng.lng()
}); //save info
document.getElementById('output').innerHTML = JSON.stringify(markersinfo);
} else {
window.alert('No results found');
}
},
function(status) {
window.alert('Geocoder failed due to: ' + status);
});
});
}
function geocodeLatLng(geocoder, latLng, success, error) {
var location = {
lat: latLng.lat(),
lng: latLng.lng()
};
geocoder.geocode({
'location': location
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
success(results);
} else {
error(status);
}
});
}
html,
body {
height: 220px;
margin: 0;
padding: 0;
}
#map {
height: 220px;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?signed_in=false&callback=initMap" async defer>
</script>
<div id='output' />
You can gather your info in the same area where you're putting info in your infowindow. Just save your lat / long, etc to a string or array. You haven't been very clear about what content should be shown (other than lat / long), or what is clicked to trigger the display. So this code will need to be adjusted to suit your specific needs.
Example:
var contentString = "";
if (results[1]) {
//...
var contentString += "Location: " + latlng + "<br />";
}
//perhaps add trigger this on an event, depending on what you want.
$('#myDiv').append(contentString);
And then your div to hold the content:
<div id="myDiv"></div>
How do I make a simple map in Jquery that plots only one location. Here is the code I have now. this plots an array of locations, but I just need a simple map that will plot one point in Lng,Lat format. I am using the google geocoder for this.
var geocoder;
var map;
var markersArray = [];
var bounds;
var infowindow = new google.maps.InfoWindow({
content: ''
});
function initialize() {
geocoder = new google.maps.Geocoder();
bounds = new google.maps.LatLngBounds();
var myOptions = {
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder.geocode({
'address': '5th Avenus New Yort'
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
bounds.extend(results[0].geometry.location);
markersArray.push(marker);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
plotMarkers();
}
var locationsArray = [
['Google Official', '1600 Amphitheatre Parkway, Mountain View, USA'],
['Google 1', '112 S. Main St., Ann Arbor, USA'],
['Google 2', '10 10th Street NE, Suite 600 USA']
];
function plotMarkers() {
var i;
for (i = 0; i < locationsArray.length; i++) {
codeAddresses(locationsArray[i]);
}
}
function codeAddresses(address) {
geocoder.geocode({
'address': address[1]
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(address[0]);
infowindow.open(map, this);
});
bounds.extend(results[0].geometry.location);
markersArray.push(marker);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
map.fitBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I then call this in my file with:
<body>
<div id="map_canvas" style="width: 100%; height: 700px;"></div>
</body>
</html>
I need the new map to plot one lat and lng point along with posting the listing the location in the textbook as above. I can not figure out how to do this without an array.
It seems like you're using an example that shows multiple markers.
I haven't tested it, but I think this JavaScript is close:
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);
geocoder.geocode( { 'address': '5th Avenue New York' }, 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);
Review this for more information: https://developers.google.com/maps/documentation/javascript/geocoding
I have a webpage to find latitude, longitude, and get a marker for that position. I use Google Maps.
My webpage get 2 addresses from user input, address 1 and address 2, and calls codeAddress()
<div id="panel">
<input id="address1" type="textbox" value="">
<input id="address2" type="textbox" value="">
<input type="button" value="find!" onclick="codeAddress()">
</div>
This is my JavaScript code:
var map;
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;
function initialize() {
var latlng = new google.maps.LatLng(-7.275920, 112.791871);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var gc = google.maps.Geocoder();
gc.geocode({
'address': address1
}, function (res1, status) {
if (status == google.maps.GeocoderStatus.OK) {
gc.geocode({
'address': address2
}, function (res2, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: res1[0].geometry.location,
map: map
});
new google.maps.Marker({
position: res2[0].geometry.location,
map: map
});
}
});
}
});
}
When I click the button find, I didn’t get the markers. Can any body help me?
Modify the codeAddress function like this:
function codeAddress() {
var gc = new google.maps.Geocoder(); // notice new keyword
initialize(); // Calling initialize. If you skip it, maps aren't loading
gc.geocode({
'address': address1
}, function(res1, status) {
if (status == google.maps.GeocoderStatus.OK) {
gc.geocode({
'address': address2
}, function(res2, status) {
if (status == google.maps.GeocoderStatus.OK) {
new google.maps.Marker({
position: res1[0].geometry.location,
map: map
});
new google.maps.Marker({
position: res2[0].geometry.location,
map: map
});
}
});
}
});
Make sure both of the inputs have some value to test it.
Demo: http://jsfiddle.net/lotusgodkk/GCu2D/213/
update the address variables from the form when the function runs
function codeAddress() {
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;
check for status != OK
} else alert("Geocode failed of " + address1 + ", status=" + status);
use "new" before the google maps Geocoder constructor
var gc = new google.maps.Geocoder();
remove existing markers before displaying new ones so the markers don't accumulate on the map
if (marker1 && marker1.setMap) marker1.setMap(null);
complete code:
var map = null;
var marker1 = null;
var marker2 = null;
var gc = new google.maps.Geocoder();
function initialize() {
var latlng = new google.maps.LatLng(-7.275920, 112.791871);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress();
}
function codeAddress() {
var address1 = document.getElementById('address1').value;
var address2 = document.getElementById('address2').value;
gc.geocode({
'address': address1
}, function (res1, status) {
if (status == google.maps.GeocoderStatus.OK) {
gc.geocode({
'address': address2
}, function (res2, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (marker1 && marker1.setMap) marker1.setMap(null);
marker1 = new google.maps.Marker({
position: res1[0].geometry.location,
map: map
});
if (marker2 && marker2.setMap) marker2.setMap(null);
marker2 = new google.maps.Marker({
position: res2[0].geometry.location,
map: map
});
} else alert("Geocode failed of " + address2 + ", status=" + status);
});
} else alert("Geocode failed of " + address1 + ", status=" + status);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
working fiddle