Google map search by address - javascript

how can I search by location(address).
I want to pass the location to my map. Now I have added lat, long.
Or is there a quick way to find out the lat and long with javascript?
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(40.0000, -98.0000), Here I want to just add the location for example Dublin, Ireland
mapTypeId: google.maps.MapTypeId.ROADMAP
}
http://jsfiddle.net/pc7Uu/346
Thanks for your help.
Best

It is called Geocoding, it is actually very easy to use, read the The Google Maps Geocoding API to get started, since you are using JavaScript you don't need an API_KEY so you can actually convert addresses to lat/lng values with requests like this:
https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
You will get a JSON with the coordinates inside the "location" key, like this:
...
"location" : {
"lat" : 37.4220352,
"lng" : -122.0841244
},
...
There are changes from V2 to V3 (recommended). Here are both documentations in case you want use an specific version:
V3 API: http://code.google.com/apis/maps/documentation/geocoding/
V2 API: http://code.google.com/apis/maps/documentation/services.html#Geocoding
If you want autocomplete functionality and/or site name to lat/lng coordinates, check the Place Autocomplete Hotel Search example.

Google Maps Geocoding API is intended for that purpose, the below example shows how to set map center based on the provided address:
//Data
var cities = [
{
city : 'Toronto',
desc : 'This is the best city in the world!',
lat : 43.7000,
long : -79.4000
},
{
city : 'New York',
desc : 'This city is aiiiiite!',
lat : 40.6700,
long : -73.9400
},
{
city : 'Chicago',
desc : 'This is the second best city in the world!',
lat : 41.8819,
long : -87.6278
},
{
city : 'Los Angeles',
desc : 'This city is live!',
lat : 34.0500,
long : -118.2500
},
{
city : 'Las Vegas',
desc : 'Sin City...\'nuff said!',
lat : 36.0800,
long : -115.1522
}
];
//Angular App Module and Controller
angular.module('mapsApp', [])
.controller('MapCtrl', function ($scope) {
var mapOptions = {
zoom: 4,
//center: new google.maps.LatLng(40.0000, -98.0000),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
var setMapCenterByAddress = function(map,address) {
var geocoder = new google.maps.Geocoder();
if (geocoder) {
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,
title: address
});
}
else {
console.log("Geocoding failed: " + status);
}
});
}
};
setMapCenterByAddress($scope.map,'Dublin, Ireland');
});
<script src="http://maps.googleapis.com/maps/api/js?key=&sensor=false"></script>
<script src="http://code.angularjs.org/1.2.25/angular.js"></script>
<script src="map.js"></script>
<style>
#map {
height:420px;
width:600px;
}
</style>
<div ng-app="mapsApp" ng-controller="MapCtrl">
<div id="map"></div>
</div>

I think your present code won't do what you are trying to do.
First, here's what the code needs to do, in plain English. I will explain each part later.
1. Send a request to the Google Geocoding API : This request will include the address you are trying to find lat&lng for. You will receive a response in the form of JSON, which you will parse to get the information you need.
2. Save the information (latitude and longitude) in a variable
3. Create a map, and use the lat&lng you found above as its center.
Okay, now here are the sources for the code. Don't worry, these code samples are very straightforward and you will easily understand what to do.
How to send the 'GET' request:
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
document.body.className = 'ok';
} else {
document.body.className = 'error';
}
}
};
request.open("GET", url , true);
request.send(null);
The http request for geocoding:
https://developers.google.com/maps/documentation/geocoding/intro#GeocodingRequests
Here is what the code will look like: (example)
var json = https://maps.googleapis.com/maps/api/geocode/json?address=1600+"ADD ADDRESS HERE"&key=YOUR_API_KEY;
var object = JSON.parse(json);
Then you can extract the lat&lng from this object.
After that, create a map using: (link) www.developers.google.com/maps/tutorials/fundamentals/adding-a-google-map
(Use the latitude and longitude you extracted above as the 'center' of the google map you will create)

I used this plugin it is very simple:
https://ubilabs.github.io/geocomplete/
alternative free service of geo location to coordinates you can use openstreet map, you can combine this with jquery autocomplete
http://nominatim.openstreetmap.org/search/

Related

ESRI TypeError: this.spatialReference is undefined

I'm using Esri GIS to load center location from address. But I use geocoder from google to get longitude and latitude. I'm stuck with this error:
TypeError: this.spatialReference is undefined
Do you have any idea for this problem?
this is my code:
require(["esri/map", "esri/geometry/Point", "esri/symbols/SimpleMarkerSymbol", "esri/symbols/PictureMarkerSymbol", "esri/graphic", "esri/layers/GraphicsLayer", "dojo/domReady!" ],
function(Map, Point, SimpleMarkerSymbol, PictureMarkerSymbol, Graphic, GraphicsLayer) {
var point = new Point(0, 0, new esri.SpatialReference({ wkid: gisMap['wkid'] }));
map = new Map(mapHolder, {center: point,zoom: gisMap['zoomlevel']});
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': keyword}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude= results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
console.log(longitude+"|"+latitude);
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
map.centerAt(new Point(longitude,latitude));
console.log(map);
} else {
console.log("No results found");
}
} else {
console.log("Something got wrong " + status);
}
});
});
The issue is in your initialization of the new esri.SpatialReference. You're not actually providing any information -- wkid is short for 'well known ID' and doesn't actually communicate any information to the API.
Since you didn't specify the version of the JS API you're using (3.x and 4.x are quite different), I can't post proper code to show you how it should be done, but these two resources:
https://developers.arcgis.com/javascript/latest/api-reference/esri-geometry-SpatialReference.html
and
https://developers.arcgis.com/javascript/3/jsapi/spatialreference-amd.html
should show you how the method should be used!

Multiple markers in flask google map api

I'm creating a flask app and try to fetch coordinates from mysql DB, the database has latitude and longitude infomation, I'd like to show all of markers on the page with the lat/lng and tend to using js to add markers, don't know why it doesn't work. Any helps appreciated.
using flask sqlalchemy to get lat/lng info
<script>
$(document).ready(function () {
function initMap() {
var latlng = {lat: -37.8253632, lng: 144.1404107}; // THIS IS CENTER OF THE MAP
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: latlng
});
google.maps.event.addListenerOnce(map, 'tilesloaded', addMarkers);
function addMarkers() {
{% for CarD in page_data %}
var point = {lat: {{ CarD.lat }}, lng: {{ CarD.lng }} };
var marker = new google.maps.Marker({
position: point,
map: map,
title: '!'
});
{% endfor %}
marker['infowindow'] = new google.maps.InfoWindow({
content: '<div id="content" style="text-align: center"></div>'
}); // info of the point
}
}
});
</script>
Your jinja templates are processed on the server side so putting the python variables in javascript only works if the js is in your template (as in you have the html and js in the same .html file). Additionally, i would discourage you from mixing the code. I would recommend you make an ajax call and receive a json response with your points. In flask you can do something like this
#app.route('/api/coordinates)
def coordinates():
addresses = session.query(Coordinates)#however you query your db
all_coods = [] # initialize a list to store your addresses
for add in addresses:
address_details = {
"lat": add.lat,
"lng": add.lng,
"title": add.title}
all_coods.append(address_details)
return jsonify({'cordinates': all_coods})
then in your javascript you can call this endpoint then process the json object (I like to use fetch for my ajax calls)
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: new google.maps.LatLng(-33.91722, 151.23064),
mapTypeId: 'roadmap'
});
//variable to hold your endpoint
var coodAddresses = 'https://yoursite.com/api/coordinates';
//an array to hold your cordinates
var locations = [];
//Using fetch to process the ajax call
// if you use fetch, besure to include the source below this line in your template
//<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.js"></script>
fetch(coodAddresses)
.then(function(response) {
return response.text();
}).then(function(body) {
var obj = JSON.parse(body);
var myAdd = {};
var addresses = obj.cordinates;
var l = addresses.length;
for (i = 0; i < l; i++) {
myAdd = {
position: {
lat: parseFloat(obj.cordinates[i].lat),
lng: parseFloat(obj.cordinates[i].lng)
},
title: obj.cordinates[i].title,
};
locations.push(myAdd);
}
locations.forEach(function(feature) {
var marker = new google.maps.Marker({
position: feature.position,
title: feature.title,
map: map
});
});
}).catch(function() {
// if the ajax call fails display an error in an info window
var pos = {
lat: lat,
lng: lng
};
infoWindow.setMap(map);
infoWindow.setPosition(pos);
infoWindow.setContent('An error occurred, we are unable to retreive cordinates.');
});
}
I hope you find this useful. If your points are not near each other, you may need to make sure the bounds include all of them

Getting Latitude and Longitude from Google Places search api using Javascript

How do I get the longitude and latitude from the searched location with the google maps place search box api.
Im using the same code as the google demo - https://developers.google.com/maps/documentation/javascript/examples/places-searchbox
function GetLatlong() {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('textboxid').value;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
});
}
You can use the above function which will give you the latitude and longitude for the area entered by user.
The code on the link you provide shows a function to do when a search is entered. First, it creates an empty array of markers (the pins you see on the map once you perform a search).
So, check the function starting with:
google.maps.event.addListener(searchBox, 'places_changed', function() {
You'll see later on that a marker has been created (there's even a comment):
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
So, on place.geometry.location you have a Google Maps Location object. You could use place.geometry.location.lat() and place.geometry.location.lng().
Check here, too: https://stackoverflow.com/a/15315483/1012139
From the docs:
// Autocomplete Options
var defaultBounds = new google.maps.LatLngBounds();
var options = {
types: ['(cities)'],
bounds: defaultBounds
};
// get DOM's input element
var input = document.getElementById('location_address');
// Make Autocomplete instance
var autocomplete = new google.maps.places.Autocomplete(input, options);
// Listener for whenever input value changes
autocomplete.addListener('place_changed', function() {
// Get place info
var place = autocomplete.getPlace();
// Do whatever with the value!
console.log(place.geometry.location.lat());
});
HTML:
<input type="text" id="address" name="address" value=""> //Autocomplete input address
<input type="hidden" name="s_latitude" id="s_latitude" value="" /> //get latitude
<input type="hidden" name="s_longitude" id="s_longitude" value="" /> //get longitude
Javascript:
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap"
async defer></script>
<script>
var input = document.getElementById('address');
var originLatitude = document.getElementById('s_latitude');
var originLongitude = document.getElementById('s_longitude');
var originAutocomplete = new google.maps.places.Autocomplete(input);
originAutocomplete.addListener('place_changed', function(event) {
var place = originAutocomplete.getPlace();
if (place.hasOwnProperty('place_id')) {
if (!place.geometry) {
// window.alert("Autocomplete's returned place contains no geometry");
return;
}
originLatitude.value = place.geometry.location.lat();
originLongitude.value = place.geometry.location.lng();
} else {
service.textSearch({
query: place.name
}, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
originLatitude.value = results[0].geometry.location.lat();
originLongitude.value = results[0].geometry.location.lng();
}
});
}
});
</script>
navigator.geolocation.getCurrentPosition(success => {
console.log(success) // `have the lat and long`
}, failure =>{
//`enter code here if failed`
});

Javascript Function - Convert Geolocation Code to Street Address

I am looking for a javascript function or jquery library to convert geolocation code (e.g. 42.2342,32.23452) to street address
For examples.
navigator.geolocation.getCurrentPosition(
function(pos) {
$("#lat_field").val(pos.coords.latitude);
$("#long_field").val(pos.coords.longitude);
}
);
Here is a google api URL to get address data
http://maps.googleapis.com/maps/api/geocode/json?latlng=41.03531125,29.0124264&sensor=false
I want to see "formatted_address" : "Hacı Hesna Hatun Mh., Paşa Limanı Cd 2-26, 34674 Istanbul, Türkiye",
navigator.geolocation.getCurrentPosition(
function(pos) {
$("#lat_field").val(pos.coords.latitude);
$("#long_field").val(pos.coords.longitude);
$("#adress_data").getaddrfromlatlong(pos.coords.latitude,pos.coords.longitude)
}
);
This function should be how ?
``getaddrfromlatlong()
Try this:
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
var latLng = new google.maps.LatLng(41.03531125,29.0124264);
if (geocoder) {
geocoder.geocode({ 'latLng': latLng}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].formatted_address);
}
else {
console.log("Geocoding failed: " + status);
}
});
}
</script>
I haven't done it in Javascript but I did something similar using the google maps web service to download XML and parse the data out of it. They also have a JSON interface as well which is likely what you'd want to use. It really is rather trivial (download the data, then grep it) so I don't think you'll need a prewritten library for it.

Get address coordinates of Google Maps API by ajax() request

I'm trying to get lng and lat coordinates of the Google Maps API by the next example http://jsbin.com/inepo3/7/edit. I expect a 'success' popup, but it keeps showing the 'Error' popup.
The google maps-request gives the correct json feedback (checked by firebug).
<script type="text/javascript">
$().ready(function() {
$.fn.getCoordinates=function(address){
$.ajax(
{
type : "GET",
url: "http://maps.google.com/maps/api/geocode/json",
dataType: "jsonp",
data: {
address: address,
sensor: "true"
},
success: function(data) {
set = data;
alert(set);
},
error : function() {
alert("Error.");
}
});
};
$().getCoordinates("Amsterdam, Netherlands");
});
</script>
Does anyone know how to fix this issue?
Regards,
Guido Lemmens
EDIT
I found a bether solution using the Google Maps Javascript API combined in jQuery:
<script type="text/javascript">
$().ready(function() {
var user1Location = "Amsterdam, Netherlands";
var geocoder = new google.maps.Geocoder();
//convert location into longitude and latitude
geocoder.geocode({
address: user1Location
}, function(locResult) {
console.log(locResult);
var lat1 = locResult[0].geometry.location.lat();
var lng1 = locResult[0].geometry.location.lng();
$("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>");
});
});
</script>
Google Map API V3 makes it harder for external libraries to work with JSONP. Here is a blog post about it.
JSONP and Google Maps API Geocoder Plus A Fix w/ jQuery
An alternative way of getting Geocoding is to use the Google Map V3 API Geocoder Service. Here is an example that i helped a person that was having a similar issue as you to replace his JSONP to use Google Map V3 Geocoder Service. Take a look at this JSFiddle Demo:
This is basically the core. We basically use twitter to get the tweet's address (IE. London, Madrid or Georgia etc) and convert the actual address into LatLng using Google Map's Geocoder Service:
$.getJSON(
url1, function(results) { // get the tweets
var res1 = results.results[0].text;
var user1name = results.results[0].from_user;
var user1Location = results.results[0].location;
// get the first tweet in the response and place it inside the div
$("#last-tweet1").html(res1 + "<p>from: " + user1name + " (" + user1Location + ")</p><p>");
//convert location into longitude and latitude
geocoder.geocode({
address: user1Location
}, function(locResult) {
console.log(locResult);
var lat1 = locResult[0].geometry.location.lat();
var lng1 = locResult[0].geometry.location.lng();
$("#testDiv").html("latitude:" + lat1 + "<p>longitude:" + lng1 + "</p>");
});
});

Categories

Resources