I am doing programming in codeigniter + ajax + javascript and I have to fetch the longitude and latitude based on the user's entry in textbox.
I am already get the right response from the controller but view is not able to convert those longitude and latitude into maps even maps are not load on the page.
Here you can see my code:
$(document).ready(function() {
function submitMe(selector)
{
//alert(selector);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/locationcontroller/getLocation",
data: {location:selector },
success:function(longitude){
// alert(selector);
locate=longitude.split(" ");
latlong(locate[0],locate[1],selector);
}
});
}
$('#address').blur(function(){
var add=$('#address').val();
// alert(add);
submitMe(add);
});
});
function latlong(lat,long,selector)
{
alert(lat);
alert(long);
var selector=selector;
var myLatlng = new google.maps.LatLng(lat,long);
var map;
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function initialize(){
var mapOptions = {
zoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("myMap"), mapOptions);
marker = new google.maps.Marker({
map: map,
position: myLatlng,
draggable: true
});
geocoder.geocode({'latLng': myLatlng }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#latitude,#longitude').show();
selector=results[0].formatted_address;
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
selector=results[0].formatted_address;
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
}
#myMap {
height: 350px;
width: 680px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<form method="POST">
<div id="myMap"></div>
<!--<input id="" type="text" style="width:600px;"/><br/>-->
<input type="text" id="address" name="address" />
<input type="text" id="latitude" placeholder="Latitude"/>
<input type="text" id="longitude" placeholder="Longitude"/>
<input type="submit" name="submit">
</form>
code of view
code of the controller
Change your javascript to
$(document).ready(function () {
function submitMe(selector) {
//alert(selector);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/locationcontroller/getLocation",
data: { location: selector },
//success: function (longitude) {
error: function (longitude) { // error because jsfiddle doesn't support ajax
//alert(selector);
longitude = "1.0001203013 12.0000001";
locate = longitude.split(" ");
latlong(locate[0], locate[1]);
}
});
}
$('#address').blur(function () {
var add = $('#address').val();
// alert(add);
submitMe(add);
});
});
function latlong(lat, long) {
alert(lat);
alert(long);
var myLatlng = new google.maps.LatLng(lat, long);
initialize(myLatlng);
}
// RELEVANT CHANGE: move initialize function outside of latlng, and receives the coordinates as parameter.
function initialize(myLatlng) {
var map;
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var mapOptions = {
zoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("myMap"), mapOptions);
marker = new google.maps.Marker({
map: map,
position: myLatlng,
draggable: true
});
geocoder.geocode({ 'latLng': myLatlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#latitude,#longitude').show();
selector = results[0].formatted_address;
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
google.maps.event.addListener(marker, 'dragend', function () {
geocoder.geocode({ 'latLng': marker.getPosition() }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
selector = results[0].formatted_address;
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', function () {
// RELEVANT CHANGE: initialize function receives an initial value.
var initialLatlng = new google.maps.LatLng(1.55555, 10.55555);
initialize(initialLatlng);
});
#myMap {
height: 350px;
width: 680px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<form method="POST">
<div id="myMap"></div>
<!--<input id="" type="text" style="width:600px;"/><br/>-->
<input type="text" id="address" name="address" />
<input type="text" id="latitude" placeholder="Latitude"/>
<input type="text" id="longitude" placeholder="Longitude"/>
<input type="submit" name="submit" />
</form>
Relevant changes
move initialize function outside of latlng, and now receives the
coordinates as parameter.
initialize function receives an initial value
JSFiddle demo
Related
I am working on core PHP, i wants to fecth location based record.
i want exact search for google map,like if i search (implemented autocomplete search) for (BTM layout) means BTM layout google map should come how will do this please help any one.
Here is my HTML form:
<form action="pglist.php" id="location_search" class="form-inline" method="POST" >
<div class="form-group keyword">
<input id="locationTextField" name= "list" type="text" size="50">
<button type="submit" name="filter"><img src="assets/images/search.png" alt="Rentozy" /></button>
</div>
</form>
Here is my database query:
$locations=array();
$query = $conn->query('SELECT `pg_address` FROM `tbl_master_property`');
while ($row = $query->fetch_assoc()) {
$locations[] = $row['pg_address'];
}
$locations = json_encode($locations);
Here my google map script code:
<div class="map">
<div id="map"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyBAM5Cs2VsrOBs8Idqy0t0o6vw4hEU0Lys">
</script>
<script type="text/javascript">
var delay = 100;
var infowindow = new google.maps.InfoWindow();
var latlng = new google.maps.LatLng(12.9716, 77.5946);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var bounds = new google.maps.LatLngBounds();
function geocodeAddress(address, next) {
geocoder.geocode({address:address}, function (results,status)
{
if (status == google.maps.GeocoderStatus.OK) {
var p = results[0].geometry.location;
var lat=p.lat();
var lng=p.lng();
createMarker(address,lat,lng);
}
else {
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
nextAddress--;
delay++;
} else {
}
}
next();
}
);
}
function createMarker(add,lat,lng) {
var contentString = add;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
animation: google.maps.Animation.DROP,
draggable: true,
map: map,
});
marker.addListener('click', toggleBounce);
function toggleBounce() {
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
bounds.extend(marker.position);
}
var locations = <?= $locations ?>;
console.log(locations);
var nextAddress = 0;
function theNext() {
if (nextAddress < locations.length) {
setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
nextAddress++;
} else {
map.fitBounds(bounds);
}
}
theNext();
</script>
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': 'BTM layout'}, function(results, status) {
if (status === 'OK') {
Map.setCenter(results[0].geometry.location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
You could request the location using geocoder and handle exceptions.
I am having google map with 20 markers popup window is there.
Now, I want to capture details of all the markers show up as list(one by one). How can I do this below?
I have pasted my whole code HTML+Javascript
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Search Near by location</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<style type="text/css">
#map {
height: 400px;
width: 600px;
border: 1px solid #333;
margin-top: 0.6em;
}
</style>
<script type="text/javascript">
$(function(){
//get the checked nearby place
$('.case').click(function(){
$(':checkbox').attr('checked',false);
$('#'+$(this).attr('id')).attr('checked',true);
search_types(map.getCenter());
});
});
var map;
var infowindow;
var markersArray = [];
var pyrmont = new google.maps.LatLng(20.268455824834792, 85.84099235520011);
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
// var waypoints = [];
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 14
});
infowindow = new google.maps.InfoWindow();
//document.getElementById('directionsPanel').innerHTML='';
search_types();
}
function createMarker(place,icon) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon,
visible:true
});
markersArray.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent("<b>Name:</b>"+place.name+"<br><b>Address:</b>"+place.vicinity+"<br><b>Reference:</b>"+place.reference+"<br><b>Rating:</b>"+place.rating+"<br><b>Id:</b>"+place.id);
infowindow.open(map, this);
//get the clicked ATM name
document.getElementById("demo").innerHTML=place.name;
// get the ATM address
document.getElementById("demo1").innerHTML=place.vicinity;
});
}
var source="";
var dest='';
function search_types(latLng){
clearOverlays();
if(!latLng){
var latLng = pyrmont;
}
var type = $('.case:checked').val();
var icon = "https://cdn2.iconfinder.com/data/icons/banking-7/24/banking-atm-1-48.png";
var request = {
location: latLng,
radius: 2500,
types: [type] //e.g. school, restaurant,bank,bar,city_hall,gym,night_club,park,zoo
};
var service = new google.maps.places.PlacesService(map);
service.search(request, function(results, status) {
map.setZoom(14);
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
results[i].html_attributions='';
createMarker(results[i],icon);
}
}
});
}
// Deletes all markers in the array by removing references to them
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(false)
}
//markersArray.length = 0;
//document.getElementById("demo3").innerHTML = markersArray.length;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
function clearMarkers(){
$('#show_btn').show();
$('#hide_btn').hide();
clearOverlays()
}
function showMarkers(){
$('#show_btn').hide();
$('#hide_btn').show();
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(true)
}
}
}
function showMap(){
var imageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=FFFFFF,008CFF,000000&ext=.png';
var markerImage = new google.maps.MarkerImage(imageUrl,new google.maps.Size(24, 32));
var input_addr=$('#address').val();
geocoder.geocode({address: input_addr}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(latitude, longitude);
if (results[0]) {
map.setZoom(14);
map.setCenter(latlng);
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: markerImage,
draggable: true
});
$('#btn').hide();
$('#latitude,#longitude').show();
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
search_types(marker.getPosition());
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#btn').hide();
$('#latitude,#longitude').show();
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
}
infowindow.setContent(results[0].formatted_address);
var centralLatLng = marker.getPosition();
search_types(centralLatLng);
infowindow.open(map, marker);
}
});
});
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
</SCRIPT>
</head>
<body>
<label>Address: </label><input id="address" type="text" style="width:400px;" value=""/>
<label class="btn btn-primary">
<input type="checkbox" name="mytype" class="case btn btn-primary" id="btn" value="atm" onClick="showMap();">ATM
</label>
<br/>
<div id="map"></div>
<input type="text" id="latitude" style="display:none;" placeholder="Latitude"/>
<input type="text" id="longitude" style="display:none;" placeholder="Longitude"/>
<!-- <input type="button" id="hide_btn" value="hide markers" onClick="clearMarkers();" />-->
<input type="button" id="show_btn" value="atm" onClick="showMarkers();" style="display:none;" />
<div id="test"></div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo3"></p>
</body>
</html>
One option would be to capture the data you want to display under the map in a appropriately scoped variable as you create the markers (in the createMarker function):
htmlStr += "<tr><td><b>Name:</b>" + place.name + "<br><b>Address:</b>" + place.vicinity + "<br><b>Reference:</b>" + place.reference + "<br><b>Rating:</b>" + place.rating + "<br><b>Id:</b>" + place.id + "</td></tr>";
Initialize the variable before the loop that creates the markers, finish it and put it in the div you want to display it at the end of the loop:
if (status == google.maps.places.PlacesServiceStatus.OK) {
htmlStr = "<table border='1'><tbody>";
for (var i = 0; i < results.length; i++) {
results[i].html_attributions = '';
createMarker(results[i], icon);
}
document.getElementById("demo").innerHTML = htmlStr + "</tbody></table>";
}
code snippet:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Search Near by location</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<style type="text/css">
#map {
height: 400px;
width: 600px;
border: 1px solid #333;
margin-top: 0.6em;
}
</style>
<script type="text/javascript">
$(function() {
//get the checked nearby place
$('.case').click(function() {
$(':checkbox').attr('checked', false);
$('#' + $(this).attr('id')).attr('checked', true);
search_types(map.getCenter());
});
});
var map;
var htmlStr = '';
var infowindow;
var markersArray = [];
var pyrmont = new google.maps.LatLng(20.268455824834792, 85.84099235520011);
var marker;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function initialize() {
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 14
});
infowindow = new google.maps.InfoWindow();
search_types();
}
function createMarker(place, icon) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon,
visible: true
});
markersArray.push(marker);
htmlStr += "<tr><td><b>Name:</b>" + place.name + "<br><b>Address:</b>" + place.vicinity + "<br><b>Reference:</b>" + place.reference + "<br><b>Rating:</b>" + place.rating + "<br><b>Id:</b>" + place.id + "</td></tr>";
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent("<b>Name:</b>" + place.name + "<br><b>Address:</b>" + place.vicinity + "<br><b>Reference:</b>" + place.reference + "<br><b>Rating:</b>" + place.rating + "<br><b>Id:</b>" + place.id);
infowindow.open(map, this);
});
}
var source = "";
var dest = '';
function search_types(latLng) {
clearOverlays();
if (!latLng) {
var latLng = pyrmont;
}
var type = $('.case:checked').val();
var icon = "https://cdn2.iconfinder.com/data/icons/banking-7/24/banking-atm-1-48.png";
var request = {
location: latLng,
radius: 2500,
types: [type] //e.g. school, restaurant,bank,bar,city_hall,gym,night_club,park,zoo
};
var service = new google.maps.places.PlacesService(map);
service.search(request, function(results, status) {
map.setZoom(14);
if (status == google.maps.places.PlacesServiceStatus.OK) {
htmlStr = "<table border='1'><tbody>";
for (var i = 0; i < results.length; i++) {
results[i].html_attributions = '';
createMarker(results[i], icon);
}
document.getElementById("demo").innerHTML = htmlStr + "</tbody></table>";
}
});
}
// Deletes all markers in the array by removing references to them
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(false)
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
function clearMarkers() {
$('#show_btn').show();
$('#hide_btn').hide();
clearOverlays()
}
function showMarkers() {
$('#show_btn').hide();
$('#hide_btn').show();
if (markersArray) {
for (i in markersArray) {
markersArray[i].setVisible(true)
}
}
}
function showMap() {
var imageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=FFFFFF,008CFF,000000&ext=.png';
var markerImage = new google.maps.MarkerImage(imageUrl, new google.maps.Size(24, 32));
var input_addr = $('#address').val();
geocoder.geocode({
address: input_addr
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(latitude, longitude);
if (results[0]) {
map.setZoom(14);
map.setCenter(latlng);
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: markerImage,
draggable: true
});
$('#btn').hide();
$('#latitude,#longitude').show();
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
search_types(marker.getPosition());
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({
'latLng': marker.getPosition()
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#btn').hide();
$('#latitude,#longitude').show();
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
}
infowindow.setContent(results[0].formatted_address);
var centralLatLng = marker.getPosition();
search_types(centralLatLng);
infowindow.open(map, marker);
}
});
});
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
$(function() {
// add multiple select / deselect functionality
$("#selectall").click(function() {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function() {
if ($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
</SCRIPT>
</head>
<body>
<label>Address:</label>
<input id="address" type="text" style="width:400px;" value="" />
<label class="btn btn-primary">
<input type="checkbox" name="mytype" class="case btn btn-primary" id="btn" value="atm" onClick="showMap();">ATM
</label>
<br/>
<div id="map"></div>
<input type="text" id="latitude" style="display:none;" placeholder="Latitude" />
<input type="text" id="longitude" style="display:none;" placeholder="Longitude" />
<!-- <input type="button" id="hide_btn" value="hide markers" onClick="clearMarkers();" />-->
<input type="button" id="show_btn" value="atm" onClick="showMarkers();" style="display:none;" />
<div id="test"></div>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo3"></p>
</body>
</html>
I think, MarkersArray contains everything you need. Lets loop trough it.
for(i=0;i<MarkersArray;i++){
marker=MarkersArray[i];
container=document.body;//change to your element
//create a new paragraph, and add it to the marker (if you need to change it later)
marker.html=document.createElement("p");
//add the name and vicinity to the paragraph
marker.html.innerHTML=marker.name+":"+marker.vicinity;
//put it on the site (into the container)
container.appendChild(marker.html);
}
I have created my code below with the mouseover affect at the end, but it does not work. Have I put it in the wrong place? I just can't seem to get it to work. Eventually I would like to get a certain type of info displayed on them but each step at a time, trying to get the basic to work first.
<!DOCTYPE html>
<html>
<head>
<!-- Google Maps and Places API -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
//declare namespace
var up206b = {};
//declare map
var map;
function trace(message)
{
if (typeof console != 'undefined')
{
console.log(message);
}
}
up206b.initialize = function()
{
var latlng = new google.maps.LatLng(52.136436, -0.460739);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
var geocoder = new google.maps.Geocoder();
up206b.geocode = function()
{
var addresses = [ $('#address').val(), $('#address2').val()];
addresses.forEach(function(address){
if(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
});
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
}
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
</script>
</head>
<body onload="up206b.initialize()">
<div style="top: 0; right: 0; width:380px; height: 500px; float:right;padding-left:10px; padding-right:10px;">
<h1 align="center">Map Search</h1>
<div style="border:1px solid #ccc; background:#e5e5e5; padding:10px;" >
<form >
<br>
Location 1 <input type="text" id="address">
<br>
<br>
Location 2
<input type="text" id="address2">
<br>
<br>
<input type="button" value="Submit" onClick="up206b.geocode()">
</form>
</div>
</div>
<div id="map_canvas" style="height: 500px; width: 500px; float:right"></div>
You need to:
define contentString
associate the marker with the infowindow content. One way of doing that is with anonymous function closure as in this related question Google Maps JS API v3 - Simple Multiple Marker Example, or with an explicit createMarker function as in my example below.
Note: This approach will only work for approximately 10 addresses, after which it will run into the Geocoder rate limits.
function createMarker(latlng, html, map) {
var infowindow = new google.maps.InfoWindow({
content: html
});
var marker = new google.maps.Marker({
map: map,
position: latlng
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
}
proof of concept fiddle
code snippet:
var markers = [];
function createMarker(latlng, html, map) {
var infowindow = new google.maps.InfoWindow({
content: html
});
var marker = new google.maps.Marker({
map: map,
position: latlng
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
markers.push(marker);
}
//declare namespace
var up206b = {};
//declare map
var map;
function trace(message) {
if (typeof console != 'undefined') {
console.log(message);
}
}
up206b.initialize = function() {
var latlng = new google.maps.LatLng(52.136436, -0.460739);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
up206b.geocode();
}
var geocoder = new google.maps.Geocoder();
up206b.geocode = function() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds();
var addresses = [$('#address').val(), $('#address2').val()];
addresses.forEach(function(address) {
if (address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
createMarker(results[0].geometry.location, address, map);
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
}
google.maps.event.addDomListener(window, "load", up206b.initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="address" value="New York, NY" />
<input id="address2" value="Newark, NJ" />
<input type="button" value="Submit" onClick="up206b.geocode()">
<div id="map_canvas"></div>
I Have a google map on my site. Users can drag the marker and the map will input the lat and lon into a form for me. See code below. I want to be able to get the address from the lat and lon and put it into my form at "locationbox".
<script src="multi_step_form.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
<script type="text/javascript">
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(49.25302534866034,-102.04825518471148);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.HYBRID
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
draggable: true,
position: myLatlng,
map: map,
title: "Your location"
});
google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
});
}
</script>
I have another bit of code to look up the address that I got from https://203luv.wordpress.com/2011/10/21/google-maps-javascript-v3-api-how-to-get-address-from-coordinates-latitude-longitude/ but I just can't figure out how to blend them together.
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
var lat = "12.1234";
var long = "98.7654";
var latlng = new google.maps.LatLng(sLat, sLong);
geocoder.geocode({"latLng":latlng},function(data,status){
if(status == google.maps.GeocoderStatus.OK){
var add = data[1].formatted_address; //this is the full address
alert(add);
for(var i=0; i<data[1].address_components.length; i++){
if(results[1].address_components[i].types[0] == "administrative_area_level_1"){
alert(results[1].address_components[i].short_name);
}
}
}
})
My html form looks like this
<div id="map_canvas" style="width: 450px; height: 450px; background-color: Black;"></div>
<div id="latlong">
<p><input size="20" type="text" id="latbox" name="lat" placeholder="Drag the marker on the map or type in the latitude"></p>
<p><input size="20" type="text" id="lngbox" name="lon" placeholder="Drag the marker on the map or type in the longitude"></p>
</div>
<input class="text_field" id="locationbox" name="location" placeholder="Location" type="text" >
Any help would be appreciated
I would suggest calling the reverse geocoder in the dragend event listener function:
google.maps.event.addListener(marker, 'dragend', function (event) {
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
var latlng = this.getPosition();
geocoder.geocode({
"latLng": latlng
}, function (data, status) {
if (status == google.maps.GeocoderStatus.OK) {
var add = data[1].formatted_address; //this is the full address
// alert(add);
for (var i = 0; i < data[1].address_components.length; i++) {
if (data[1].address_components[i].types[0] == "administrative_area_level_1") {
document.getElementById('locationbox').value = data[1].address_components[i].short_name;
}
}
}
});
});
proof of concept fiddle
code snippet:
var map;
function initialize() {
var geocoder = new google.maps.Geocoder();
var myLatlng = new google.maps.LatLng(49.25302534866034, -102.04825518471148);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
draggable: true,
position: myLatlng,
map: map,
title: "Your location"
});
google.maps.event.addListener(marker, 'dragend', function(event) {
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
var latlng = this.getPosition();
geocoder.geocode({
"latLng": latlng
}, function(data, status) {
if (status == google.maps.GeocoderStatus.OK) {
var add = data[1].formatted_address; //this is the full address
// alert(add);
for (var i = 0; i < data[1].address_components.length; i++) {
if (data[1].address_components[i].types[0] == "administrative_area_level_1") {
document.getElementById('locationbox').value = data[1].address_components[i].short_name;
}
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas" style="width: 450px; height: 450px; background-color: Black;"></div>
<div id="latlong">
<p>
<input size="20" type="text" id="latbox" name="lat" placeholder="Drag the marker on the map or type in the latitude">
</p>
<p>
<input size="20" type="text" id="lngbox" name="lon" placeholder="Drag the marker on the map or type in the longitude">
</p>
</div>
<input class="text_field" id="locationbox" name="location" placeholder="Location" type="text">
JS Fiddle: http://jsfiddle.net/SULSV/
I use the following code to display a map on my website:
My HTML:
<div id="myMap" style="height:350px;width:680px"></div>
<input id="address" type="text" style="width:600px;"/>
<input type="text" id="latitude" placeholder="Latitude"/>
<input type="text" id="longitude" placeholder="Longitude"/>
My JS:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false">
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script type="text/javascript">
var map;
var marker;
var myLatlng = new google.maps.LatLng(20.268455824834792, 85.84099235520011);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
function initialize() {
var mapOptions = {
zoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("myMap"), mapOptions);
marker = new google.maps.Marker({
map: map,
position: myLatlng,
draggable: true
});
geocoder.geocode({
'latLng': myLatlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#latitude,#longitude').show();
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
google.maps.event.addListener(marker, 'dragend', function () {
geocoder.geocode({
'latLng': marker.getPosition()
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#address').val(results[0].formatted_address);
$('#latitude').val(marker.getPosition().lat());
$('#longitude').val(marker.getPosition().lng());
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
}
}
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
My question: What code do I need to add in order to add a street view box under the map which is linked to the roadmap and shows the current position of the marker?
I alerady know that it is possible to initialize streetview by
new google.maps.StreetViewPanorama(document.getElementById("DIV-BOX"));
but I have no clue how to integrate streetview into my code.
define it via the streetView-property of the map:
var mapOptions = {
zoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetView: new google.maps.StreetViewPanorama(document.getElementById("DIV-BOX"))
};
http://jsfiddle.net/SULSV/1/