If I were to search for a textual address (Let's say the address is "305 Quincy St NE"), how would I go about doing it in ArcGIS using the ArcGIS API for Javascript?
My aim is to call a function which has the geometry of a place passed as its function argument.
function showLocation(evt) {
map.graphics.clear();
var point = evt.result.feature.geometry; // how do I get this value from a textual address?
.
.
.
}
Use the Locator class. Here's an example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Using Locator to Find Address</title>
<link rel="stylesheet" href="https://js.arcgis.com/3.14/esri/css/esri.css">
<style>
html, body, #map {
height:100%;
width:100%;
margin:0;
padding:0;
}
body {
background-color:#FFF;
overflow:hidden;
font-family:"Trebuchet MS";
}
#search {
display: block;
position: absolute;
z-index: 2;
top: 20px;
left: 75px;
}
</style>
<script src="https://js.arcgis.com/3.14/"></script>
<script>
var map;
var locator;
var symbol;
var locatorUrl = "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer";
require([
"esri/map", "esri/tasks/locator", "esri/graphic",
"esri/Color", "esri/symbols/SimpleMarkerSymbol", "esri/symbols/SimpleLineSymbol",
"dijit/form/TextBox", "dijit/registry", "dojo/on", "dojo/parser",
"dojo/keys",
"dojo/domReady!"
], function(
Map, Locator, Graphic,
Color, SimpleMarkerSymbol, SimpleLineSymbol,
TextBox, registry, on, parser,
keys
) {
map = new Map("map",{
basemap: "topo",
center: [-117.19, 34.05],
zoom: 13
});
locator = new Locator(locatorUrl);
symbol = new SimpleMarkerSymbol(
SimpleMarkerSymbol.STYLE_CIRCLE,
20,
new SimpleLineSymbol(
SimpleLineSymbol.STYLE_SOLID,
Color.fromHex("#EEAA00"),
3),
Color.fromHex("#002255")
);
parser.parse();
var box = registry.byId("textBox_address");
on(box, "keypress", function (evt) {
if (keys.ENTER == evt.keyCode) {
var addressText = box.get("value");
//This is the important part. Call Locator.addressToLocations.
locator.addressToLocations({
address: {
SingleLine: addressText
}
}, function (addresses) {
//Success
if (0 == addresses.length) {
alert("Address not found");
} else {
var address = addresses[0];
var pt = address.location;
map.graphics.clear();
map.graphics.add(new Graphic(pt, symbol));
map.centerAt(pt);
}
}, function (error) {
//Failure
alert("Error: " + error);
});
}
});
});
</script>
</head>
<body>
<div id="search">
<label for="firstname" style="background-color: white">Address:</label>
<input type="text" name="textBox_address" value="808 Travis St, Houston TX"
data-dojo-type="dijit/form/TextBox" id="textBox_address" />
</div>
<div id="map"></div>
</body>
</html>
var address = "305 Quincy St NE";
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var longitude= results[0].geometry.location.lat();
var latitude = results[0].geometry.location.lng();
}
});
Regarding to Hiren's answer,
THe problem is not with the latitude and longitude, the problem is that you can not use Google Geocoder with any other technology different than Google Maps:
The Geocoding API may only be used in conjunction with a Google map;
geocoding results without displaying them on a map is prohibited. For
complete details on allowed usage, consult the Maps API Terms of
Service License Restrictions.
You can check it here:
https://developers.google.com/maps/documentation/geocoding/intro
Cheers!
Related
I have a simple MVC application in which i want to show location dynamically from Google map.
I am getting this Error in this file----
Unhandled exception at line 16, column 59007 in https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js
0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'getElementsByTagName'
The View page contains simple html with javaScript code and some javaScript files included----
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Google Maps </h1>
<div align="left">
<input type="text" value="" id="searchbox" style=" width:800px;height:30px; font-size:10px; margin-top: 7px;">
</div>
<div align="left" id="map" style="width:800px; height: 600px; margin-top: 10px;">
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function () {
var mapOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.06000, 28.98700)
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var geocoder = new google.maps.Geocoder();
$(function () {
$("#searchbox").autocomplete({
source: function (request, response) {
if (geocoder == null) {
geocoder = new google.maps.Geocoder();
}
geocoder.geocode({ 'address': request.term }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var searchLoc = results[0].geometry.location;
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(lat, lng);
var bounds = results[0].geometry.bounds;
geocoder.geocode({ 'latLng': latlng }, function (results1, status1) {
if (status1 == google.maps.GeocoderStatus.OK) {
if (results1[1]) {
response($.map(results1, function (loc) {
return {
label: loc.formatted_address,
value: loc.formatted_address,
bounds: loc.geometry.bounds
}
}));
}
}
});
}
});
},
select: function (event, ui) {
var pos = ui.item.position;
var lct = ui.item.locType;
var bounds = ui.item.bounds;
if (bounds) {
map.fitBounds(bounds);
}
}
});
});
});
Want to answer my own question...................I think those old javaScript library file were not compatible with the new versions of IE9. So, I just changed the referenced js libraries files to latest one from this page....developers.google.com/speed/libraries and everything is working fine now....
you can include jquery migrate js file in your project to resolve this. http://code.jquery.com/jquery-migrate-1.2.1.js
I wish I can put this as a comment but I dont have enough reps...
0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'Show'
The error above led me to this question and when I didn't find my answer, I looked at it again and the answer was much simpler - I miss-typed 'show' as 'Show'.
$('#Member').closest('.form-group').Show();
I changed it back to lowercase 's'- .show() - I hope this alerts someone else.
I add letest version of jquery and solved problem...
Like...."jquery-1.10.2.js"
.
..
I am not sure how to go about this.
What I want:
I want to display the information that you might find if you were to go to https://www.google.com/maps and search for the farmers' market.
I want an Info window that provides the address, hours of operation, and possibly additional information that Google Maps provides for this business.
What I have now:
I have an Angular JS code block that populates an array that looks like the following:
var locations = [
['Findlay Market', 39.115398, -84.518481, 5],
['Hyde Park Farmers' Market', 39.139601, -84.442496, 4],
['Lettuce Eat Well Farmers' Market', 39.166134, -84.611613, 3],
['College Hill Farm Market', 39.195641, -84.545453, 2],
['Anderson Farmers' Market', 39.078364, -84.350539, 1]
];
Then I use the Infowindow to display the name of the farmers market.
I know that I could add a new table to my database for hours and additional information and use that to create an Angular JS card that I could display in the Infowindow... BUT I was hoping there would be a way to use the Google Map API with the Google Places API to get that information instead of storing it in my database.
Thanks to uksz I was able to use the below code to help me get the information I needed.
<!DOCTYPE html>
<html>
<head>
<title>Place details</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<script>
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(39.115398, -84.518481),
zoom: 15
});
var request = {
location: map.getCenter(),
radius: '500',
query: 'Findlay Market'
};
var service = new google.maps.places.PlacesService(map);
service.textSearch(request, callback);
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
place: {
placeId: results[1].place_id,
location: results[1].geometry.location
}
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function() {
var content = results[1].name + '<br>' +
results[1].formatted_address + '<br>' +
results[1].opening_hours + '<br>' +
results[1].place_id + '<br>';
infowindow.setContent(content);
infowindow.open(map, this);
});
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
So I don't know if I understood your question correctly, but if you only want to display the information from Google Places API, you can use theirs getDetails() function. This will return an object. If you don't want to store the object, why not just deleting the object after each time the user for example switches the view? This way you will not store this information in your database, at least not permanently.
Have a good one!
Here is their full getDetails() manual:
https://developers.google.com/maps/documentation/javascript/places#place_details_requests
I am running a queryTask in order to select dynamicMapServiceLayers on my map. I am able to get a popup window for my polygon features (campus buildings) but cannot seem to get the Bus Stop layers to return anything. I looked to reconfigure the point layer itself but did not find any results on here or arcGIS online. I've looked at a ton of sample code and haven't yet seen anything that changes anything specific about point features. Is there something I am missing to return a popup window for my point features(Bus Stops)?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--The viewport meta tag is used to improve the presentation and behavior of the samples
on iOS devices-->
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Updating the legend to display visible layers</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.11/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://js.arcgis.com/3.11/esri/css/esri.css">
<style>
html, body {
height: 97%;
width: 98%;
margin: 1%;
}
#rightPane {
width: 20%;
}
#legendPane {
border: solid #97DCF2 1px;
}
</style>
<script src="http://js.arcgis.com/3.11/"></script>
<script>
dojo.require("esri.tasks.query");
dojo.require("esri.dijit.Popup");
dojo.require("esri.tasks.find");
dojo.require("");
var map, queryTask, query;
var symbol, markerSymbol, infoTemplate;
require([
"esri/map",
"esri/arcgis/utils",
"esri/dijit/Legend",
"esri/layers/ArcGISDynamicMapServiceLayer",
"dojo/dom",
"dojo/dom-construct",
"dojo/parser",
"dojo/_base/array",
"dijit/form/CheckBox",
"dijit/layout/AccordionContainer",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dojo/domReady!"
],
function (
Map, utils, Legend, ArcGISDynamicMapServiceLayer, dom, domConstruct,
parser, arrayUtils, CheckBox
) {
parser.parse();
var legendLayers = [];
map = new Map("map", {
basemap: "topo",
center: [-80.556, 37.1367],
zoom: 16
});
var buildingLayer = new ArcGISDynamicMapServiceLayer("http://geog-grant.radford.edu/arcgiscloud/rest/services/RU/MapServer", {
id: 'ruRestServices'
});
legendLayers.push({ layer: buildingLayer, title: 'RU Rest Services' });
map.on('layers-add-result', function () {
var legend = new Legend({
map: map,
layerInfos: legendLayers
}, "legendDiv");
legend.startup();
});
map.addLayers([ buildingLayer ]);
map.on('layers-add-result', function () {
//add check boxes
arrayUtils.forEach(legendLayers, function (layer) {
var layerName = layer.title;
var checkBox = new CheckBox({
name: "checkBox" + layer.layer.id,
value: layer.layer.id,
checked: layer.layer.visible
});
checkBox.on("change", function () {
var targetLayer = map.getLayer(this.value);
targetLayer.setVisibility(!targetLayer.visible);
this.checked = targetLayer.visible;
});
//add the check box and label to the toc
domConstruct.place(checkBox.domNode, dom.byId("toggle"), "after");
var checkLabel = domConstruct.create('label', {
'for': checkBox.name,
innerHTML: layerName
}, checkBox.domNode, "after");
domConstruct.place("<br />", checkLabel, "after");
});
});
dojo.connect(map, "onClick", executeQueryTask);
queryTask = new esri.tasks.QueryTask("http://geog-grant.radford.edu/arcgiscloud/rest/services/RU/MapServer/6");
queryTask2 = new esri.tasks.QueryTask("http://geog-grant.radford.edu/arcgiscloud/rest/services/RU/MapServer/4");
query = new esri.tasks.Query();
query.returnGeometry = true;
query.outFields = ["BLDGNAME", "OBJECTID", "NAME", "SHAPE_AREA" ];
query2 = new esri.tasks.Query();
query.returnGeometry = true;
query2.outFields = ["OBJECTID"];
infoTemplate = new esri.InfoTemplate("${BLDGNAME}", "Object ID: ${OBJECTID}<br />Name: ${Name}");
infoTemplate2 = new esri.InfoTemplate("${OBJECTID}", "Object ID: ${OBJECTID}" );
markerSymbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE, 20, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255,0,0]), 2), new dojo.Color([255,255,0,0.5]));
polygonSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT, new dojo.Color([255,0,0]), 2), new dojo.Color([255,255,0,0.5]));
});
function executeQueryTask(evt) {
query.geometry = evt.mapPoint;
queryTask.execute(query, showResults);
}
function executeQueryTask2(evt) {
query2.geometry = evt.mapPoint;
queryTask2.execute(query2, showResults2);
}
function showResults(featureSet) {
map.graphics.clear();
dojo.forEach(featureSet.features,function(feature){
var graphic = feature;
switch (graphic.geometry.type){
case "point":
graphic.setSymbol(markerSymbol);
break;
case "polygon":
graphic.setSymbol(polygonSymbol);
break;
}
// graphic.setSymbol(symbol);
graphic.setInfoTemplate(infoTemplate);
graphic.setInfoTemplate(infoTemplate2);
map.graphics.add(graphic);
});
}
</script>
</head>
<body class="claro">
Click on a Radford University Building to get more info. When Building is highlighted, click building again to get info window.
<!--[if IE 7]>
<style>
html, body {
margin: 0;
}
</style>
<![endif]-->
<div id="content" data-dojo-type="dijit/layout/BorderContainer"
data-dojo-props="design:'headline', gutters:true"
style="width: 100%; height: 100%; margin: 0;">
<div id="rightPane"
data-dojo-type="dijit/layout/ContentPane"
data-dojo-props="region:'right'">
<div data-dojo-type="dijit/layout/AccordionContainer">
<div data-dojo-type="dijit/layout/ContentPane" id="legendPane"
data-dojo-props="title:'Legend', selected:true">
<div id="legendDiv"></div>
</div>
<div data-dojo-type="dijit/layout/ContentPane"
data-dojo-props="title:'RU Layers'">
<span style="padding:10px 0;">Click to toggle the RU Rest API Service Layers</span>
<div id="toggle" style="padding: 2px 2px;"></div>
</div>
</div>
</div>
<div id="map"
data-dojo-type="dijit/layout/ContentPane"
data-dojo-props="region:'center'"
style="overflow:hidden;">
</div>
</div>
</body>
</html>
Any help is appreciated.
There is more than one error in your code.
The most important is that when querying a point layer you should build an Extent as a filter geometry, and not a point. That extent must contain the point you're querying. Here are the fixes:
//dojo.connect(map, "onClick", executeQueryTask); WRONG
dojo.connect(map, "onClick", executeQueryTask2);
.....
query2 = new esri.tasks.Query();
//query.returnGeometry = true; WRONG
query2.returnGeometry = true;
query2.outFields = ["OBJECTID"];
.....
function executeQueryTask(evt) {
// clear goes here so that it clears only before first query
map.graphics.clear();
query.geometry = evt.mapPoint;
queryTask.execute(query, showResults);
}
function executeQueryTask2(evt) {
// query2.geometry = evt.mapPoint; WRONG
var ext = new esri.geometry.Extent(evt.mapPoint.x - 50, evt.mapPoint.y - 50 , evt.mapPoint.x + 50, evt.mapPoint.y + 50, evt.mapPoint.spatialReference)
query2.geometry = ext;
queryTask2.execute(query2, showResults);
}
function showResults(featureSet) {
dojo.forEach(featureSet.features,function(feature){
var graphic = feature;
switch (graphic.geometry.type){
case "point":
graphic.setSymbol(markerSymbol);
// set info template for points
graphic.setInfoTemplate(infoTemplate2);
break;
case "polygon":
graphic.setSymbol(polygonSymbol);
// set info template for polygons
graphic.setInfoTemplate(infoTemplate);
break;
}
map.graphics.add(graphic);
});
}
I'm trying to execute two separate functions from one onClick.
It is a dictionary service which returns definitions from Glosbi API and the second function is Google Maps API call that changes the map to what has been searched for.
The first functions works perfectly, but the second function calling Google Maps API doesn't work.
Can anyone see anything in my code that isn't right or needs to be changed? I feel very close!
function codeTerm() {
$(document).ready(function(){
$('#term').focus(function(){
var full = $("#definition").has("definition").length ? true : false;
if(full === false){
$('#definition').empty();
}
});
var getDefinition = function(){
var word = $('#term').val();
if(word === ''){
$('#definition').html("<h2 class='loading'>We haven't forgotten to validate the form! Please enter a word.</h2>");
}
else {
$('#definition').html("<h2 class='loading'>Your definition is on its way!</h2>");
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=" +word+ "&pretty=true&callback=?", function(json) {
if (json !== "No definition has been found."){
var meanings = "";
json["tuc"].forEach(function(tuc) {
if (typeof tuc["meanings"] !== 'undefined') {
tuc["meanings"].forEach(function(m) {
meanings += "<p>"+m["text"]+"</p>\n";
});
}
});
$("#definition").html(meanings);
}
else {
$.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=&pretty=true" + "?callback=?", function(json) {
console.log(json);
$('#definition').html('<h2 class="loading">Nothing found.</h2><img id="thedefinition" src=' + json.definition[0].image.url + ' />');
});
}
});
}
return false;
};
$('#search').click(getDefinition);
$('#term').keyup(function(event){
if(event.keyCode === 13){
getDefinition();
}
});
});
}
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 country = document.getElementById('search').value;
geocoder.geocode( { 'search': country}, 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);
$('#search').click(country);
$('#term').keyup(function(results){
if(results.keyCode === 13){
country();
}
});
And the HTML
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="author" content="Matthew Hughes">
<meta name="Dictionary" content="A dictionary web service">
<title>Dictionary Web Application</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="dictionary.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCVD1Kaf1yE4M9IcBNRAyujObcY2sGI0J0&sensor=false"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="dictionary.js"></script>
</head>
<body>
<div id="container">
<div id="top">
<header>
<h1>Dictionary Application</h1>
</header>
</div>
<div id="app">
<div id="panel">
<input id="term" type="text" placeholder="Enter a word...">
<button id="search" onclick="codeTerm(); codeAddress();">Define!</button>
</div>
<section id="definition">
</section>
<div id="map-canvas">
</div>
</div>
<footer>
<p>Created by Matthew Hughes</p>
</footer>
</div>
</body>
Thanks!
In the comments you mention 2 errors...
google is not defined
Was the inclusion of the Google API successful? You have this:
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCVD1Kaf1yE4M9IcBNRAyujObcY2sGI0J0&sensor=false"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
Do those references work? In your browser debugging tools, take a look at the network tab. What do these calls return, if anything? It sounds like the API isn't being loaded successfully. Do you need those to be https specifically? Try omitting the protocol so that it defaults to the current page's protocol:
<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyCVD1Kaf1yE4M9IcBNRAyujObcY2sGI0J0&sensor=false"></script>
<script src="//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
You're also including one of your JavaScript libraries twice:
<script src="dictionary.js"></script>
That might not break anything, but it also might. In any event, it should only be included once.
country if not defined
You create a variable called country in one of your functions:
function codeAddress() {
var country = document.getElementById('search').value;
// other code
}
So it's scope is within that function only. But you also try to reference it outside of that function, and you try to reference it as a function:
$('#search').click(country);
$('#term').keyup(function(results){
if(results.keyCode === 13){
country();
}
});
So even if it were moved to a global scope, country isn't a function so it's not clear what you're trying to accomplish with these two handlers. Maybe you meant to invoke a different function?
I am trying to add a Google autocomplete search box to a website so that users can search for an address as easily as possible.
My problem is, I have looked a numerous questions on here as well as the Google Maps Javascript API v3 regarding this and some tutorials yet they all bundle together the autocomplete functionality with mapping it on an embedded Google map.
I don't need to map the location visually, I just need the autocomplete box for now, unfortunately I cannot work out which parts of the API are relevant to this and every example I have looked at includes plenty of JS for mapping.
How can I ONLY add the autocomplete input functionality?
A significant portion of this code can be eliminated.
HTML excerpt:
<head>
...
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
...
</head>
<body>
...
<input id="searchTextField" type="text" size="50">
...
</body>
Javascript:
function initialize() {
var input = document.getElementById('searchTextField');
new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);
To get latitude and longitude too, you can use this simple code:
<html>
<head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
<script>
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
document.getElementById('city2').value = place.name;
document.getElementById('cityLat').value = place.geometry.location.lat();
document.getElementById('cityLng').value = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />
<input type="hidden" id="city2" name="city2" />
<input type="hidden" id="cityLat" name="cityLat" />
<input type="hidden" id="cityLng" name="cityLng" />
</body>
</html>
To use Google Maps/Places APIs now, you're required to use an API Key. So the API URL will change from
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
to
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
Just copy and paste the sameple code below.
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/jsvv=3.exp&sensor=false&libraries=places"></script>
</head>
<body>
<label for="locationTextField">Location</label>
<input id="locationTextField" type="text" size="50">
<script>
function init() {
var input = document.getElementById('locationTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', init);
</script>
</body>
</html>
Well formatted code can be found from this link.
http://jon.kim/how-to-add-google-maps-autocomplete-search-box/
So I've been playing around with this and it seems you need both places and js maps api activated. Then use the following:
HTML:
<input id="searchTextField" type="text" size="50">
<input id="address" name="address" value='' type="hidden" placeholder="">
JS:
<script>
function initMap() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
document.getElementById("address").value = JSON.stringify(place.address_components);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap" async defer></script>
Use Google Maps JavaScript API with places library to implement Google Maps Autocomplete search box in the webpage.
HTML
<input id="searchInput" class="controls" type="text" placeholder="Enter a location">
JavaScript
<script>
function initMap() {
var input = document.getElementById('searchInput');
var autocomplete = new google.maps.places.Autocomplete(input);
}
</script>
Complete guide, source code, and live demo can be found from here - Google Maps Autocomplete Search Box with Map and Info Window
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(poenter code heresition) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
<input id="autocomplete" placeholder="Enter your address" type="text"/>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="https://mapenter code heres.googleapis.com/maps/api/js?key=AIzaSyC7vPqKI7qjaHCE1SPg6i_d1HWFv1BtODo&libraries=places"></script>
<script type="text/javascript">
function initialize() {
new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')), {
types: ['geocode']
});
}
initialize();
</script>
Follow the below code.
Add this to your TS file.
declare this, top of your class.
declare var google;
declare the view child for Map and the input.
#ViewChild('mapElement', {static: true}) mapNativeElement: ElementRef;
#ViewChild('autoCompleteInput', {static: true}) inputNativeElement: any;
this method is run on ngOnInit() event or ngAfterViewInit() event.
autoComplete() {
const map = new google.maps.Map(this.mapNativeElement.nativeElement, {
center: {lat: -33.8688, lng: 151.2093},
zoom: 7
});
const infowindow = new google.maps.InfoWindow();
const infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
const marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
const autocomplete = new google.maps.places.Autocomplete(this.inputNativeElement.nativeElement as HTMLInputElement);
autocomplete.addListener('place_changed', () => {
infowindow.close();
marker.setVisible(false);
const place = autocomplete.getPlace();
let cus_location = {
lat: place.geometry.location.lat(),
long: place.geometry.location.lng()
}
console.log('place data :................', cus_location);
localStorage.setItem('LOC_DATA', this.helper.encryptData(cus_location));
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert('No details available for input: ' + place.name );
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
let address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
if(infowindowContent){
infowindowContent.children['place-icon'].src = place.icon;
infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = address;
}
infowindow.open(map, marker);
});
}
calling the method on ngAfterViewInit.
ngAfterViewInit(): void {
this.autoComplete();
}
And this is the HTML code. please modify as per your need.
<ion-content fullscreen>
<div class="location-col">
<div class="google-map">
<!-- <img src="../../assets/images/google-map.jpg" alt=""> -->
<div #mapElement id="map"></div>
</div>
<div class="location-info">
<h2>Where is your car located?</h2>
<p>Enter address manually or click location detector icon to use current address.</p>
<div class="form-group">
<div class="location-row">
<input type="text" #autoCompleteInput class="location-input" [(ngModel)]="search_location" placeholder="Search location">
<span class="location-icon" (click)="getCurrentLocation()">
<img src="../../assets/images/location-icon.svg" alt="">
</span>
</div>
<button type="button" class="location-search-btn" (click)="goToVendorSearch()">
<i class="fa fa-angle-right"></i>
</button>
</div>
</div>
</div>
</ion-content>
I am currently using the Google API to retrieve the location that the user enters in the form/ input. I'm also using an angular function that showing the current location and suggests a city name pin code etc...
- add google API index.html.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxx&libraries=geometry,places"></script>
- add id in input box to get string & charcters.
<input id="autocomplete" type="text"(keydown)="checkAddress($event.target.value)">
- and create function on your component.ts file.
import these file
import * as _ from 'lodash';
declare var google: any;
checkAddress(value) {
if (!value) {
this.model.location = _.cloneDeep(value);
this.rfpForm.controls['location'].setValue(this.model.location);
}
}
initLocationAutocomplete() {
let autocomplete, place;
const getLocation = () => {
place = autocomplete.getPlace();
if (place && (place.formatted_address || place.name)) {
// if you want set value in your form controls like this
this.model.location = _.cloneDeep(place.formatted_address || place.name);
// YourFormName.controls['location'].setValue(this.model.location);
// YourFormName.controls['location']['_touched'] = true;
}
};
autocomplete = new google.maps.places.Autocomplete((document.getElementById('autocomplete')), { types: ['geocode'] });
autocomplete.addListener('place_changed', getLocation);
}
<input type="text"required id="autocomplete">
<script>
function initAutocomplete() {
new google.maps.places.Autocomplete(
(document.getElementById('autocomplete')),
{types: ['geocode']}
);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=&libraries=places&callback=initAutocomplete"
async defer></script>
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete Address Form</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<script>
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.
var placeSearch, autocomplete;
var componentForm = {
street_number: 'short_name',
route: 'long_name',
locality: 'long_name',
administrative_area_level_1: 'short_name',
country: 'long_name',
postal_code: 'short_name'
};
function initialize() {
// Create the autocomplete object, restricting the search
// to geographical location types.
autocomplete = new google.maps.places.Autocomplete(
/** #type {HTMLInputElement} */(document.getElementById('autocomplete')),
{ types: ['geocode'] });
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
fillInAddress();
});
}
// [START region_fillform]
function fillInAddress() {
// Get the place details from the autocomplete object.
var place = autocomplete.getPlace();
for (var component in componentForm) {
document.getElementById(component).value = '';
document.getElementById(component).disabled = false;
}
// Get each component of the address from the place details
// and fill the corresponding field on the form.
for (var i = 0; i < place.address_components.length; i++) {
var addressType = place.address_components[i].types[0];
if (componentForm[addressType]) {
var val = place.address_components[i][componentForm[addressType]];
document.getElementById(addressType).value = val;
}
}
}
// [END region_fillform]
// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geolocation = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
var circle = new google.maps.Circle({
center: geolocation,
radius: position.coords.accuracy
});
autocomplete.setBounds(circle.getBounds());
});
}
}
// [END region_geolocation]
</script>
<style>
#locationField, #controls {
position: relative;
width: 480px;
}
#autocomplete {
position: absolute;
top: 0px;
left: 0px;
width: 99%;
}
.label {
text-align: right;
font-weight: bold;
width: 100px;
color: #303030;
}
#address {
border: 1px solid #000090;
background-color: #f0f0ff;
width: 480px;
padding-right: 2px;
}
#address td {
font-size: 10pt;
}
.field {
width: 99%;
}
.slimField {
width: 80px;
}
.wideField {
width: 200px;
}
#locationField {
height: 20px;
margin-bottom: 2px;
}
</style>
</head>
<body onload="initialize()">
<div id="locationField">
<input id="autocomplete" placeholder="Enter your address"
onFocus="geolocate()" type="text"></input>
</div>
</body>
</html>
I am using jQuery here to get the entered text and wrapping all code in $(document).ready(). Make sure you have your API key ready for Google Places API Web service. Replace it in the below script file.
<input type="text" id="location">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_KEY_HERE]&libraries=places"></script>
<script src="javascripts/scripts.js"></scripts>
Use script file to load the autocomplete class. Your scripts.js file will look something like this.
// scripts.js custom js file
$(document).ready(function () {
google.maps.event.addDomListener(window, 'load', initialize);
});
function initialize() {
var input = document.getElementById('location');
var autocomplete = new google.maps.places.Autocomplete(input);
}