Google MAPS API location from the address

Asked

Viewed 15,395 times

1

I have an address saved in the database, divided correctly and accurately from this address generate the latitude and longitude and besides this plot on the map a marked in the registered area.

SGL_ENDER_ESTAD: "MG"
TXT_ENDER_BAIRR: "MEU BAIRRO"
TXT_ENDER_CEPXX: "MEU CEP"
TXT_ENDER_CIDAD: "MINHA CIDADE"
TXT_ENDER_COMPL: null
TXT_ENDER_LOGRA: "MINHA RUA"
TXT_ENDER_NUMER: "MEU NUMERO"

I have nothing done yet on the subject as I do not know much about the API, I would like someone to help me start production, or I pass a website or video that would be as a tutorial for my problem.

One detail, I need everything to be done with Jquery or Javascript, another detail is that my project is mobile, and I use HTML5 + Cordova.

Has as ?

3 answers

9


Use the API GeoCode.

Example:

http://maps.google.com/maps/api/geocode/json?address=Avenida%20Rio%20Branco,%20Rio%20from%20Janeiro&sensor=false

Return the coordinates of Rio Branco Avenue in Rio de Janeiro:

{
   "results" : [
      {
         [...],
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : -22.8960696,
                  "lng" : -43.1737186
               },
               "southwest" : {
                  "lat" : -22.9147546,
                  "lng" : -43.1812468
               }
            },
            "location" : {
               "lat" : -22.9055697,
               "lng" : -43.1774453
            },
            "location_type" : "GEOMETRIC_CENTER",
            "viewport" : {
               "northeast" : {
                  "lat" : -22.8960696,
                  "lng" : -43.1737186
               },
               "southwest" : {
                  "lat" : -22.9147546,
                  "lng" : -43.1812468
               }
            }
         },
         "place_id" : "ChIJvxA4RV5_mQARIFeLysc-ZjY",
         "types" : [ "route" ]
      }
   ],
   "status" : "OK"
}

This API understands natural language; you can concatenate your database fields and use them in the parameter address.

Once you have the coordinates, you can use the Simple Markers API to display the map with the coordinate:

https://developers.google.com/maps/documentation/javascript/examples/marker-simple

This is an example using one of the coordinates pairs received above:

window.onload = function() {
    var latlng = new google.maps.LatLng(-22.8960696, -43.1737186);
    var map = new google.maps.Map(document.getElementById('map'), {
        center: latlng,
        zoom: 11,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: 'Set lat/lon values for this property',
        draggable: true
    });
    google.maps.event.addListener(marker, 'dragend', function(a) {
        console.log(a);
        var div = document.createElement('div');
        div.innerHTML = a.latLng.lat().toFixed(4) + ', ' + a.latLng.lng().toFixed(4);
        document.getElementsByTagName('body')[0].appendChild(div);
    });
};
#map {
  height: 300px;
  border: 1px solid #000;
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div id="map"></div>

  • I will study, but how will I get the correct lat and Lon of the address ? For in your example appeared several. and how would plot on the map ? It would have to make an example ne some site ?

  • @Renanrodrigues use the key GEOMETRIC_CENTER. This indicates, literally, the medium of the selected structure.

  • how do I pass the json information to geocoder ? Help me with this ?

  • @Renanrodrigues The Geocoder receives text (via QueryString) and returns a JSON. I updated the response with an example map view.

  • Where in your code you pass the address ?

  • @Renanrodrigues on the first link present in my reply.

  • Because this part is ok. However how will I get the lat and the long of the address I have from the database ?

  • Like I don’t know how I’ll send the link address.

  • @Renanrodrigues This is another question, which runs a little outside the scope of this. Feel free to create another question.

  • Friend take the last doubt, manage to make the request and is returning me the perfect json, however I am not able to access the lat and the long GEOMETRIC_CENTER. I’m doing next. lat = dados.geometry.location.lat and you’re not getting how I do this ?]

  • @Renanrodrigues try to dados.results.geometry.location.lat.

  • Uncaught Typeerror: Cannot read Property 'Geometry' of Undefined

  • After a long time searching, this answer helped me!

  • @Leonardomax I’m happy to read this. Enjoy!

Show 10 more comments

1

1

Following example developed with angular.

Design link: https://github.com/emirdeliz/meus-projetos/tree/master/google-maps-custom/src/main/webapp

App:

var app = angular.module("GoogleMapsCustom", ["uiGmapgoogle-maps"]);

Controller:

app.controller("GoogleMapsCustomController", function($scope) {
    $scope.map = { center: { latitude: -23.586172, longitude: -46.657085 }, zoom: 10};
    $scope.map.randomMarkers = [];
    var adressOfCustomer = [
                             ["BAZAR BARAO LTDA ME", "AV.JOAO XXIII,84-V.FORMOSA, SP"],                                          
                             ["MAGAZINE BELEZA CENTER LTDA", "AV DOS IGARAPES, 1571, SP"],                                                
                             ["ESTACIONAMENTO CARREIRA LTDA ME", "AV.SAPOPEMBA,3016 SAPOPEMBA, SP"],                                          
                             ["LUIS GONZAGA GARDINALI ME", "R.FREI CANECA,22 - CENTRO, SP"],                                             
                             ["A R NETTO", "R.ANTONIO GONCALVES TEIXEIRA, 53, SP"],                                     
                             ["O DONEGA MOJI MIRIM ", "R.BUTANTA, 17-PINHEIROS, SP"],                                               
                             ["MAGAZINE MISS ELEGAN LTDA", "R GOVERNADOR PEDRO DE TOLEDO 1021, SP"],                                   
                             ["O.Y.OKI & CIA.LTDA ", "R.JOSE BONIFACIO,60, SP"]
                         ];

    $scope.setMarkers = function(numberOfMarkers) {
        setLatitudeAndLongitudeByAdress(adressOfCustomer, $scope.map);
    };

    $scope.onMarkerClicked = function(marker){
        marker.showWindow = true;
        $scope.$apply();
    };
});

app.controller("InfoController", function($scope) {
    $scope.templateValue = 'hello from the template itself';
    $scope.clickedButtonInWindow = function() {
        var msg = 'clicked a window in the template!';
        $log.info(msg);
        alert(msg);
    }
});

function setLatitudeAndLongitudeByAdress(adressOfCustomer, map){
    var geocoder = new google.maps.Geocoder();

    angular.forEach(adressOfCustomer, function(value, key) {
        var adress = value[1];
        geocoder.geocode({ 'address': adress + ', Brasil', 'region': 'BR' }, function (results, status) {
            var latitude = results[0].geometry.location.lat();
            var longitude = results[0].geometry.location.lng();
            var customer = value[0];
            var itemMap = {
                latitude : latitude,
                longitude : longitude,
                title : customer,
                id : key,
                adress : adress,
                date : "10/11/2015"
            };
            map.randomMarkers.push(itemMap);
        });
    });
}

function init(){

    var adressOfCustomer = [
        ["BAZAR BARAO LTDA ME", "AV.JOAO XXIII,84-V.FORMOSA, SP"],                                          
        ["MAGAZINE BELEZA CENTER LTDA", "AV DOS IGARAPES, 1571, SP"],                                                
        ["ESTACIONAMENTO CARREIRA LTDA ME", "AV.SAPOPEMBA,3016 SAPOPEMBA, SP"],                                          
        ["LUIS GONZAGA GARDINALI ME", "R.FREI CANECA,22 - CENTRO, SP"],                                             
        ["A R NETTO", "R.ANTONIO GONCALVES TEIXEIRA, 53, SP"],                                     
        ["O DONEGA MOJI MIRIM ", "R.BUTANTA, 17-PINHEIROS, SP"],                                               
        ["MAGAZINE MISS ELEGAN LTDA", "R GOVERNADOR PEDRO DE TOLEDO 1021, SP"],                                   
        ["O.Y.OKI & CIA.LTDA ", "R.JOSE BONIFACIO,60, SP"]
    ];

    var locationOfCustomer = getLatitudeAndLongitudeByAdress(adressOfCustomer);
    initializeMaps(locationOfCustomer);
}

Index.html

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Google Maps API v3: Busca de endereço e Autocomplete - Demo</title>
        <link rel="stylesheet" type="text/css" href="assets/css/custom.css">

       </head>
    <body ng-app="GoogleMapsCustom">

        <h1>Google Maps Multiple Marker Demo 123</h1>


        <div ng-controller="GoogleMapsCustomController" ng-init="setMarkers();">
            <ui-gmap-google-map center="map.center" zoom="map.zoom"> <ui-gmap-markers models="map.randomMarkers" coords="'self'" icon="'icon'" click="onMarkerClicked" doCluster="map.doClusterRandomMarkers"
                clusterOptions="map.clusterOptions" modelsbyref="true"> 
                <ui-gmap-windows show="'showWindow'" closeClick="'closeClick'" ng-cloak>
                    <div>
                        <p ng-non-bindable>{{title}} - endereço: {{adress}} visita: {{date}}<button type='button'>Incluir na Agenda</button></p>
                    </div>
                    </ui-gmap-windows> 
                </ui-gmap-markers> 
            </ui-gmap-google-map>
        </div>
    </body>
</html>
  • Those arriving in this solution, the link is outdated. The current: https://github.com/emirdeliz/angular-google-maps

Browser other questions tagged

You are not signed in. Login or sign up in order to post.