Google maps get latitude and longitude having city name?

后端 未结 3 622
你的背包
你的背包 2021-01-30 04:33

I want to get latitude and longitude of a city by providing the API with the city name. It should work for most cities regardless how the user inputs the city.

For examp

3条回答
  •  忘了有多久
    2021-01-30 05:07

    Update per comment below: Doesn't work after July 2018.


    This seems needlessly complicated. Here's an example "nearby events" map. It will take City, States, convert them to latLng coords, and put markers on a map:

    // Nearby Events with Google Maps
    window.nearbyEventsMap = () => {
        const centerOfUS = {
            lat: 37.09024,
            lng: -95.712891
        }
    
        // Create a map object and specify the DOM element for display.
        const map = new google.maps.Map(document.querySelector('#nearby_events_map'), {
            center: centerOfUS,
            scrollwheel: false,
            zoom: 4
        })
    
        // Create a marker and set its position.
        const geocoder = new google.maps.Geocoder()
    
        // Filter out duplicate cityStates
        let cityStates = {}
        document.querySelectorAll('.nearby_event_city_state').forEach(event => {
            cityStates[event] = event.innerText
        })
    
        // `cityState` is in the format of "City, State". It's not picky about state being a word or the abbreviation.
        for (const cityState in cityStates) {
            const location = cityStates[cityState]
    
            geocoder.geocode({
                address: location
            }, function (results, status) {
                if (status === 'OK') {
                    const result = results[0].geometry.location
                    const lat = result.lat()
                    const lng = result.lng()
                    const latLng = {
                        lat,
                        lng
                    }
    
                    return new google.maps.Marker({
                        map: map,
                        position: latLng
                    })
                }
            })
        }
    }
    // /Nearby Events with Google Maps
    

    Make sure to include your

    StackOverflow please join everyone else and get GitHub markdown with syntax highlighting...

提交回复
热议问题