如何从autocomplete.getPlace()获得google place api的结果?

问题描述 投票:5回答:3

我想把来自google the places api的经纬度结果传递给我的MVC应用程序的动作路由值。我不知道如何将它传递到我的路由值,或者如何将javascript返回到html值。现在

var result = autocomplete.getPlace();

正在返回一个未定义的值。因此,即使自动完成地方的工作正常,它看起来也不像在工作。

var input = document.getElementById('location');
var options = {
types: ['(cities)'],
componentRestrictions: { country: "us" }
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
var t = 2;
var result = autocomplete.getPlace(); //result is undefined
var i = 1;
//var lat = result.geometry.location.lat;
//var lon = result.geometry.location.lon;

这是我的表单,它有输入框和脚本标签,在那里找到位置。我正试图将lonlat值改为路径值5,6。

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js? v=3.exp&amp;sensor=false&amp;libraries=places"></script>

@{
    var routeValues = new RouteValueDictionary();
    routeValues.Add("Longitude", "5");
    routeValues.Add("Latitude", "6");
}

@using (Html.BeginForm("Results", "Home", routeValues, FormMethod.Post))
{
    <p>
        <input type="text" name="location" id="location" placeholder="Search For A Studio" />
    </p>
    <p>
        <input class="btn btn-primary btn-lg" value='Submit' type="submit"/>
    </p>
}

以下是我在控制器中的操作

public ActionResult Results(string longitude, string latitude)
    {
        var repo = new YogaSpaceRepository();

            /// 1000 Ocean Ave
            DbGeography myLocation = DbGeography.FromText("POINT(-122.453164 37.723057)");
            IQueryable<YogaSpace> spaces = repo.AllWithinDistance(myLocation);


        return View(spaces);
    }

*更新 - 我可以让autocomplete.getPlace()返回数据。我不得不把它放在一个javascript函数中,用于我的提交按钮的onclick事件。希望这是最好的方法!但我似乎无法从中获得位置(经纬度)数据,这是我所拥有的,但latlon似乎没有我正在寻找的东西,或者也许我不知道如何从这两个变量中提取坐标。

var input = document.getElementById('location');
var options = {
   types: ['(cities)'],
   componentRestrictions: { country: "us" }
};
var autocomplete = new google.maps.places.Autocomplete(input, options);

function getGeometry() {
   var place = autocomplete.getPlace();

   var lat = place.geometry.location.lat;
   var lon = place.geometry.location.lon;
}
javascript asp.net-mvc google-maps google-maps-api-3 google-places-api
3个回答
5
投票

你可以从geometry.location对象中得到lat和lang,通过

place.geometry.location.lat()
place.geometry.location.lng()

3
投票

你是在正确的轨道上,但由于 latlng职能LatLng对象,下面的例子演示了如何获得 lat/lng:

var place = autocomplete.getPlace();
var lat = place.geometry.location.lat();
var lng = place.geometry.location.lat();

完整的例子

function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: -33.8688, lng: 151.2195 },
        zoom: 13
    });
    var input = /** @type {!HTMLInputElement} */(
        document.getElementById('pac-input'));

    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
    

    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.bindTo('bounds', map);

    var infowindow = new google.maps.InfoWindow();
    var marker = new google.maps.Marker({
        map: map,
        anchorPoint: new google.maps.Point(0, -29)
    });


    autocomplete.addListener('place_changed', function () {
        infowindow.close();
        marker.setVisible(false);
        var place = autocomplete.getPlace();
        if (!place.geometry) {
            window.alert("Autocomplete's returned place contains no geometry");
            return;
        }

        //displayResult(place);

        // If the place has a geometry, then present it on a map.
        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.setIcon(/** @type {google.maps.Icon} */({
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(35, 35)
        }));
        marker.setPosition(place.geometry.location);
        marker.setVisible(true);
        

        var 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(' ');
        }

        //infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
        infowindow.setContent('<div><strong>' + "Location(" + place.geometry.location.lat() + "," + place.geometry.location.lng() + ")" + '</strong><br>');
        infowindow.open(map, marker);
    });

}
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }

        #map {
            height: 100%;
        }

        .controls {
            margin-top: 10px;
            border: 1px solid transparent;
            border-radius: 2px 0 0 2px;
            box-sizing: border-box;
            -moz-box-sizing: border-box;
            height: 32px;
            outline: none;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
        }

        #pac-input {
            background-color: #fff;
            font-family: Roboto;
            font-size: 15px;
            font-weight: 300;
            margin-left: 12px;
            padding: 0 11px 0 13px;
            text-overflow: ellipsis;
            width: 300px;
        }

            #pac-input:focus {
                border-color: #4d90fe;
            }

        .pac-container {
            font-family: Roboto;
        }
 <input id="pac-input" class="controls" type="text"
           placeholder="Enter a location">
    <div id="map"></div>
    <script src="https://maps.googleapis.com/maps/api/js?signed_in=true&libraries=places&callback=initMap"
            async defer></script>

0
投票

我知道这是个老问题,但应该对其他人有用。

要获得几何属性,你需要为自动完成对象设置 "字段",像这样。

autocomplete.setFields(['address_component', 'geometry']);

要得到地址_组件和几何细节。

这是重要的,以限制数据的数量,你得到的数据,你将由谷歌的API收费。

阅读这个。

https:/developers.google.commapsdocumentationjavascriptplaces-autocomplete?hl=ja#get_place_information。

而这,对于getPlace()的结果。

https:/developers.google.commapsdocumentationjavascriptreferenceplaces-service?hl=ja#PlaceResult。

© www.soinside.com 2019 - 2024. All rights reserved.